rics Logo
v0.5.0

Utility functions

  • Logging configuration
  • Multivariate performance testing
  • Fetching data from remote sources
  • …and more!

ID Translation

  • Quickstart guide
  • Translation format strings
  • The Translator
  • Handling unknown IDs
  • Fetching: SQL database
  • Fetching: Local files
  • Fetching: User implementations
  • Offline translation

Documentation

  • Installation
  • Change history
  • Readme
  • License

Complete API reference

  • rics.utility package
  • rics.utility.perf package
  • rics.cardinality package
  • rics.mapping package
  • rics.translation package

Cookbook

  • Binary search
  • Git
  • Terminal
rics
  • »
  • Binary search
  • Edit on GitHub

Binary search

Template for binary search prefer lower a lower bound. Copy-paste and edit solving more complex problems.

def search(arr, v):    
    low, high = 0, len(arr)
    
    while low < high:
        mid = (low + high) // 2
        if arr[mid] == v:
            return mid
        
        if v < arr[mid]:
            high = mid
        else:
            low = mid + 1
            
    return -1

Key points

  • The choice of low/high/mid should ALWAYS shrink the bound

  • Keep in mind what happens when there are “few” elements; 0, 1, 2 may cause problems

  • This becomes plain old binary search if FOUND=True and NOT_FOUND=False.

  • The initial range should include the entire bound of things you want to find For example, we can:

    • Index where we want to insert v into arr (which may be at the edges)

Language-specific notes

C/C++

  • Iterators and size types outside their natural range.

  • high + low overflow

Python

Index -1.

Previous Next

© Copyright 2022, Richard Sundqvist. Revision 0828b61d.

Built with Sphinx using a theme provided by Read the Docs.