Skip to content

Binary search

Python while + branching

Same task in: TypeScript

Flowchart (ISO 5807)

YesYesNoYesNoNoStartInput a, keylo, hi = 0, len(a) - 1lo ≤ himid = (lo + hi) div 2a[mid] = keyReturn midEnda[mid] < keylo = mid + 1hi = mid − 1Return −1EndFigure 1 — bsearch

Source code

Python
def bsearch(a, key):
    lo, hi = 0, len(a) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if a[mid] == key:
            return mid
        elif a[mid] < key:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

The editor opens with this code — change it and the chart redraws.

Language
Python
Constructs
while + branching
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples