1.Binary search on a sorted array — O(log n)
On a sorted array, compare the target to the middle element and throw away the half it cannot be in. Repeating that halves the search space every step, giving O(log n) instead of O(n).
Key features
- Requires the input to already be sorted — binary search gives no warning if it is not, it just returns a wrong answer
- O(log n) time, O(1) extra space for the iterative version shown below
- lo and hi are both valid indices to check; the loop keeps going while lo <= hi, and stops once the search space is empty
Binary search only works on sorted data — it never checks that precondition itself, so passing unsorted data gives a wrong answer with no error.