Binary Search
Find a number in a sorted array by checking the middle and throwing away the half that cannot hold it.
Given an array of integers numstargettargetnums
Example 1
Output: 4
Example 2
Output: -1
The Idea
Think of looking up a word in a paper dictionary. You do not read it from the first page. You open it near the middle, see whether your word comes before or after that page, and keep only that half. A handful of such openings finds any word in a thick book.
The array in the examples can be searched the same way, because it is sorted. Take Example 2: is 2 in [-1, 0, 3, 5, 9, 12]
It can. Compare 2 with a number in the middle, 3 at index 2. Since 3 is bigger than 2, and every number to its right is bigger still, 2 can only be to the left of index 2. That one comparison has ruled out four of the six numbers.
The part of the array that can still hold the target is called the range. Two indexes mark it: lohimid
In the first row, lo = 0hi = 5midhimidlolo
In the last row, lo = 2hi = 1
So each comparison throws away about half of what is left. Six numbers need at most three comparisons, and a million numbers need at most 20. Splitting the range in two at every step is what gives binary search its name.
Solution Approach
Turning that idea into code means settling four things: what lohimid
The range between lo and hi
Should hilohilohilo = 0hi = nums.length - 1
Moving lo and hi
After comparing nums[mid]targetlohinums[mid]midlomid + 1himid - 1mid
When to stop
When does the search give up? Not when lohilo == hilohilo <= hi
Finding the middle without overflow
The obvious way to compute mid(lo + hi) / 2intintlo + hilo + (hi - lo) / 2hi - lo
Java Solution
The method search
- First, set
to 0 andlo tohi , so the range covers the whole array.nums.length - 1 - Start a loop that runs while
, that is, while the range still holds a number. Inside it, computelo <= hi asmid .lo + (hi - lo) / 2 - If
equalsnums[mid] , returntarget .mid - If
is smaller thannums[mid] , movetarget tolo . Otherwise it is bigger, so movemid + 1 tohi .mid - 1 - If the loop ends, the range is empty and the target is not in the array, so return -1.
The main
public class BinarySearch {
public static int search(int[] nums, int target) {
int lo = 0;
int hi = nums.length - 1; // the target, if present, is in nums[lo..hi]
while (lo <= hi) { // stop when the range is empty
int mid = lo + (hi - lo) / 2; // no overflow, unlike (lo + hi) / 2
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
lo = mid + 1; // target can only be to the right of mid
} else {
hi = mid - 1; // target can only be to the left of mid
}
}
return -1;
}
public static void main(String[] args) {
int[] nums = {-1, 0, 3, 5, 9, 12};
System.out.println(search(nums, 9));
System.out.println(search(nums, 2));
System.out.println(search(nums, 12));
System.out.println(search(nums, -5));
System.out.println(search(new int[] {5}, 5));
System.out.println(search(new int[] {}, 5));
int lo = 1500000000;
int hi = 2000000000;
System.out.println((lo + hi) / 2 + " " + (lo + (hi - lo) / 2));
}
}
Running it prints:
4
-1
5
-1
0
-1
-397483648 1750000000
The 4 and -1 at the top answer the two examples. The 5 below them is the search for 12: the range shrinks until only index 5 is left, and that last number is still compared. Searching for -5 prints -1, because every comparison moves hilo
The 0 on the fifth line comes from [5]lohiwhile (lo < hi)hi
The last line shows the overflow. (lo + hi) / 2lo + (hi - lo) / 2
The original implementation, Arrays.binarySearch(nums, target)
Complexity
The work is the number of passes of the loop, and each pass costs one comparison and a few index updates.
- Time: O(log n), because each pass at least halves the range of n numbers, so the loop runs at most about log2(n) + 1 times. An array of a million numbers needs at most 20 passes.
- Space: O(1), because the search keeps only
,lo andhi , makes no copy of the array and calls nothing recursively.mid
Variations of this loop solve many other problems;