Binary search
Binary search uses 2 pointers, i and j, marking the interval where the value can still be. They start at i = 0 and j = n β 1, the array's 2 ends. Each round, the middle is computed, m = (i + j) / 2 rounded down, and nums[m] is compared with the target. If it's smaller, the value is on the right: i becomes m + 1. If it's larger, it's on the left: j becomes m β 1. If it's equal, found.
If the value isn't there, the pointers keep closing in until they cross: when i ends up greater than j, the interval is empty and β1 is returned. The search never takes more rounds than logβ n, so even finding nothing it ends fast. And it uses O(1) memory: just the 2 pointers.
Computing the middle as (i + j) / 2 has a trap: if i and j are large integers, the sum can go past the int type's maximum and give a negative number. That's why it's usually computed as i + (j β i) / 2, which gives the same result without adding the 2 large numbers. It's a classic bug that sat for years in Java's standard library.
There are 2 common ways to write binary search. With a closed interval [i, j], both ends count: j starts at n β 1, the loop runs while i β€ j, and j = m β 1 is used. With a half-open interval [i, j), j doesn't count: it starts at n, the loop runs while i < j, and j = m is used. Both work; the closed one is more symmetric and usually causes fewer bugs.
Binary search is very fast, O(log n), and uses no extra memory. But it has limits. It needs sorted data: sorting just to search once costs O(n log n), more than a linear search. It only works on arrays, because it needs to jump to the middle in 1 step. And with very little data, linear search wins, because each of its rounds is 1 comparison while binary search does several calculations per round.
A useful way to think about binary search is to give each pointer a goal. i moves toward elements greater than or equal to the target; j moves back toward smaller ones. When the loop ends without finding, i lands on the first element greater than the target and j on the last smaller one. That idea is the base for the next level's variants: finding where to insert or where a run of duplicates starts.
