Abdul Wajid

R-05 · Lab

Live experiments

Algorithms running in the browser — search, queues, and envelope encryption with matching code panels.

04

Lab

A few algorithms running live — search, a worker queue, and encryption.

Preview

O(log n)

371114182329313742485561677388

lo=0 · mid=7 · hi=15 · target=42

Finds a value by cutting the list in half each step.

binary_search.py
1
def binary_search(xs: list[int], t: int) -> int:
2
    lo, hi = 0, len(xs) - 1
3
    while lo <= hi:
4
        mid = (lo + hi) // 2
5
        if xs[mid] == t:
6
            return mid
7
        if xs[mid] < t:
8
            lo = mid + 1
9
        else:
10
            hi = mid - 1
11
    return -1