What is Searching and Binary Search?
Solution and explanation
Searching
Searching means finding whether (and where) a target value exists in a collection.
- Linear search checks elements one by one: works on any array, O(n).
- Binary search repeatedly halves a sorted range: O(log n).
- Hashing (HashMap/HashSet) finds keys in O(1) average time.
Binary search intuition
Looking up a word in a dictionary, you open the middle; if your word comes earlier, you discard the second half, and so on. Each step halves the search space, so 1,000,000 elements need at most about 20 comparisons (2^20 ≈ 10^6).
sorted: [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target 23
low=0, high=9 → mid=4 (16) < 23 → low=5
low=5, high=9 → mid=7 (56) > 23 → high=6
low=5, high=6 → mid=5 (23) found at index 5
static int binarySearch(int[] a, int target) {
int low = 0, high = a.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2; // avoids int overflow of (low + high)
if (a[mid] == target) return mid;
if (a[mid] < target) low = mid + 1; else high = mid - 1;
}
return -1;
}
Requirements and pitfalls
- The data must be sorted (or the condition must be monotonic).
- Use mid = low + (high − low) / 2 to avoid overflow.
- Decide carefully between low <= high and low < high and how you move the bounds, or you will loop forever.
Binary search on the answer
Many problems are not about arrays at all: find the smallest capacity, speed or value x for which a yes/no check becomes true (e.g. "minimum days to ship packages"). If the check is monotonic, binary search over the range of possible answers.
Complexity
- Linear search: O(n) time, O(1) space.
- Binary search: O(log n) time, O(1) space iterative (O(log n) recursive).
