Skip to content

Binary search

TypeScript while + branching

Same task in: Python

Flowchart (ISO 5807)

YesYesNoYesNoNoStartInput a, keylo = 0hi = |a| − 1lo ≤ himid = Math.floor((lo + hi) / 2)a[mid] = keyReturn midEnda[mid] < keylo = mid + 1hi = mid − 1Return −1EndFigure 1 — bsearch

Source code

TypeScript
function bsearch(a: number[], key: number): number {
    let lo = 0, hi = a.length - 1;
    while (lo <= hi) {
        const mid = Math.floor((lo + hi) / 2);
        if (a[mid] === key) return mid;
        else if (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
TypeScript
Constructs
while + branching
Topic
Algorithms
Formats
Word, Visio, draw.io, PDF, SVG

Related examples