Lab / search
Binary Search
Each comparison with the middle element rules out half of what is left. Twelve numbers take at most four comparisons; a million take at most twenty.
Ready: low = 0, high = 11. The whole array is the search interval.
- 03
- 18
- 212
- 317
- 423
- 531
- 642
- 756
- 864
- 977
- 1085
- 1193
Invariant. If the target exists in the original sorted array, it remains inside the active search interval until it is found or the interval becomes empty. Worst case O(log n) time; this iterative version uses O(1) extra space.
All 2 steps as a table
| Step | low | high | mid | a[mid] | Decision |
|---|---|---|---|---|---|
| 1 | 0 | 11 | 5 | 31 | a[5] = 31 is less than 64, so the target can only be right of 5. Set low = 6. |
| 2 | 6 | 11 | 8 | 64 | a[8] = 64 equals the target. Found at index 8. |
What the explorer checks
- The input must be sorted in non-decreasing order. Unsorted input is reported, not silently sorted, because a search on unsorted data gives wrong answers without any error.
- Every value must be a finite number.
- With duplicates, the search returns an index holding the target, not necessarily the first one.
Why mid = low + ⌊(high − low) / 2⌋
It is the same as ⌊(low + high) / 2⌋ but never computes low + high, which can overflow in languages with fixed-width integers. In JavaScript it makes no difference; it is kept because it is the habit worth teaching.