Skip to main content
Ctrl+K
rics 6.1.3 documentation - Home rics 6.1.3 documentation - Home
  • API reference
  • Documentation
  • Development
  • License
  • Changelog
  • GitHub
  • PyPI
  • API reference
  • Documentation
  • Development
  • License
  • Changelog
  • GitHub
  • PyPI

Section Navigation

  • Examples
    • Performance
      • Pandas GroupBy row selection
      • In vs between (legacy)
    • Plotting
      • Pi ticks
      • Plotting style
  • Cookbook
    • Binary search
    • Git
    • Jupyter Notebooks
    • Sphinx documentation
    • Terminal
    • uv
  • CLI tools
    • rics
    • rics kernel
    • rics timeit
  • Documentation
  • Cookbook
  • Binary search

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

Cookbook

next

Git

On this page
  • Key points
  • Language-specific notes
    • C/C++
    • Python

© Copyright Richard Sundqvist, 2026.

Created using Sphinx 9.1.0.

Built with the PyData Sphinx Theme 0.16.1.