Part 16 / Topic 7 of 12
Binary search
Binary search finds a value in O(log n) by repeatedly halving the search range, instead of scanning element by element — but it needs sorted data, full stop. This is the one precondition in this whole part that, when skipped, doesn't crash — it just quietly returns a wrong answer. Think of looking up a name in a phone book: you don't start at "A" and read every name; you open to the middle, see which half the name must be in, and repeat — that only works because the names are already in order.
static int binarySearch(int[] sortedPincodes, int target) {
int low = 0, high = sortedPincodes.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // avoids overflow vs. (low + high) / 2
if (sortedPincodes[mid] == target) return mid;
else if (sortedPincodes[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
$ javac BinarySearchDemo.java
$ java BinarySearchDemo
sorted pincodes: [110001, 122001, 160017, 380001, 411001, 500001, 560001, 600001, 700001, 800001]
-- linear vs binary search for 560001 (near the end) --
linear search:
found in 7 step(s)
binary search:
found in 4 step(s)
index: 6
-- Arrays.binarySearch on a sorted int[] --
Arrays.binarySearch(411001): index 4
Arrays.binarySearch(999999, not present): -11 (negative: -(insertion point) - 1, here -(10)-1)
-- Collections.binarySearch on a sorted List, with a comparator --
station with code 340: Kalyan at index 2
-- the one precondition: unsorted data gives a WRONG, meaningless answer --
unsorted array: [500001, 110001, 700001, 160017]
Arrays.binarySearch(160017) on unsorted data: -3 (looks like 'not found' but 160017 IS in the array, at index 3 -- sort first, always)
Two library methods cover almost every real case: Arrays.binarySearch(int[], target) for primitive arrays, and Collections.binarySearch(list, key, comparator) for a List<T> — both return the index if found, and a negative number encoding the insertion point if not (-(insertion point) - 1, which is why -11 means "would belong at index 10"). The last block is the whole point of this section: 160017 genuinely sits at index 3 of the unsorted array, and Arrays.binarySearch still reports it missing, because it trusts the "sorted" precondition completely and never checks it for you.
⚠️
Arrays.binarySearchnever verifies the array is sorted. It is faster because it skips that check. If there's any doubt, sort first (section 6) — the cost of sorting once is almost always smaller than the cost of debugging a search that lies.
Full program: examples/binary-search/BinarySearchDemo.java.
Done here? The practice set for Part 16 — including the solutions — is on the part page.