Loading algorithms…
Loading visualizer…
Halve the search space at every step on a sorted array. The canonical O(log n) search algorithm — best case finds in 1 comparison, worst case in ⌈log₂(n+1)⌉.
Cyan = lo · Amber = mid · Rose = hi · Emerald = found · dimmed = eliminated
Every arr[mid] vs target comparison in order
No comparisons yet. Press Play or step forward.
Binary search is the canonical divide and conquer search algorithm. Given a sorted array, it repeatedly halves the search space by comparing the target to the middle element. If the target is smaller, search the left half; if larger, search the right half. At most ⌈log₂(n+1)⌉ comparisons are needed.
lo (start of the search range) and hi (end of the search range). Initially lo = 0 and hi = n - 1.mid = ⌊(lo + hi) / 2⌋. Read arr[mid].arr[mid] to the target:mid (found).lo = mid + 1 (search the right half).hi = mid - 1 (search the left half).lo > hi. At that point the search range is empty and the target is not present.💡 Sorted input is mandatory. Binary search on an unsorted array is meaningless — the comparison rules (go left / go right) rely on the array being sorted in non-decreasing order. Use merge sort (O(n log n)) or insertion sort (O(n) on nearly-sorted data) to sort first.
Binary search requires the array to be sorted. Every iteration halves the search space, so at most ⌈log₂(n+1)⌉ comparisons are needed.