Binary Search
Searching sorted data by starting in the middle and eliminating half of the remaining elements at every step: tracing low, high, and mid, iterative and recursive versions, why sorted order is required, and why binary search is usually faster than linear search.
Data must be in sorted order to use the binary search algorithm. Binary search starts at the middle of a sorted array or ArrayList and eliminates half of the remaining elements in each step until the desired value is found or all elements have been eliminated. It is typically more efficient than linear search, and it can be written either iteratively or recursively. Tracing it means tracking the range that remains, usually with variables named low and high, and the middle index checked at each step.
1Sorted Data First
Binary search is built on one fact about sorted data: if the middle element is smaller than the value being sought, then every element before it is smaller too, so none of them can be the target. One comparison therefore rules out a whole half of the data. Data must be in sorted order to use the binary search algorithm; on unsorted data that reasoning is false, and the search can discard the half that contains the target.
The order can be ascending numbers, alphabetical strings, or any order that the comparisons in the code agree with. If the data is not sorted, a linear search, which assumes nothing about order, is the correct choice, or the data must be sorted first.
Binary Search on Unsorted Data
42 is in the array below. What does each search return?
public static int binaryFind(int[] a, int target)
{
int low = 0;
int high = a.length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
if (a[mid] == target)
{
return mid;
}
else if (a[mid] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
public static int linearFind(int[] a, int target)
{
for (int i = 0; i < a.length; i++)
{
if (a[i] == target)
{
return i;
}
}
return -1;
}
-1 2
- 1Binary search assumes order.
a[3]is 8, less than 42, so it discards indices 0 to 3, including the 42 at index 2 (Figure 1). - 2Linear search assumes nothing and finds 42 at index 2.
Binary search on unsorted data compiles and runs, but it can return −1 for a value that is present, or find a different occurrence than expected. Check that the data is sorted before choosing binary search.
2Start in the Middle, Eliminate Half
Binary search keeps track of the part of the data that might still hold the target, from index low to index high. At first that is everything: low is 0 and high is the last index. Each step checks the middle index, mid = (low + high) / 2, using integer division, so the middle rounds down when the range has an even number of elements.
If the middle element equals the target, the search is over. If it is smaller than the target, the target can only be to its right, so low becomes mid + 1. If it is larger, the target can only be to its left, so high becomes mid - 1. Either way, the middle element and one half of the range are eliminated.
| Step | low | high | mid | a[mid] | Compared with 30 | Next |
|---|---|---|---|---|---|---|
| 1 | 0 | 6 | 3 | 21 | 21 < 30 | low = 4 |
| 2 | 4 | 6 | 5 | 42 | 42 > 30 | high = 4 |
| 3 | 4 | 4 | 4 | 30 | equal | return 4 |
Tracing low, high, and mid
The search prints its range before each check. Predict the output.
public static int binarySearch(int[] a, int target)
{
int low = 0;
int high = a.length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
System.out.println("low " + low + ", high " + high + ", mid " + mid);
if (a[mid] == target)
{
return mid;
}
else if (a[mid] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
low 0, high 6, mid 3
low 4, high 6, mid 5
low 4, high 4, mid 4
4
- 1Step 1. mid = (0 + 6) / 2 = 3;
a[3]is 21, less than 30, solowbecomes 4. - 2Step 2. mid = (4 + 6) / 2 = 5;
a[5]is 42, greater than 30, sohighbecomes 4. - 3Step 3. mid = (4 + 4) / 2 = 4;
a[4]is 30: return 4.
The middle element has already been checked, so the new range must exclude it. With low = mid, a range of two elements can produce the same mid forever, and the loop never ends. Use mid + 1 and mid - 1.
3Tracing Each Step
To determine the result of each iteration, keep a table with one row per step: low, high, mid, the element at mid, the comparison, and the change to the range. Compute mid with integer division every time; most tracing mistakes come from rounding mid up or reusing an old value.
The same steps apply to an ArrayList, using get(mid) and size(), and to strings, using compareTo: a result of 0 means a match, a negative result means the middle word comes earlier than the target, and a positive result means it comes later.
Comparing With compareTo
Search a sorted list of words. Predict the output.
public static int findWord(ArrayList<String> list, String target)
{
int low = 0;
int high = list.size() - 1;
while (low <= high)
{
int mid = (low + high) / 2;
int cmp = list.get(mid).compareTo(target);
if (cmp == 0)
{
return mid;
}
else if (cmp < 0)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
4
-1
- 1
compareToreturns 0 for equal strings, a negative number when the middle word comes earlier, and a positive number when it comes later. - 2"maple": mid 3 is "elm", earlier, so search right; mid 5 is "oak", later, so search left; mid 4 is "maple".
- 3"fir" would sit between "elm" and "maple"; the range empties and the result is −1.
compareTo to decide which half to keep.Relational operators do not work on String objects, and == compares references. A binary search of strings decides its direction with compareTo and detects a match with a result of 0.
4The Recursive Version
The binary search algorithm can be written either iteratively or recursively. In the recursive version, the range is passed as parameters: each call checks the middle of its range and, unless it finds the target, returns the result of a call on the half that remains. The parameters low and high capture the progress of the search, just as the loop variables do in the iterative version.
The recursive version has two base cases: a match, which returns mid, and an empty range, low > high, which returns −1. Tracing it is the same as tracing the loop, one call per step; the value found by the last call is returned unchanged through all the earlier calls.
low and high parameters.| Iterative | Recursive | |
|---|---|---|
| Range stored in | Local variables low, high | Parameters low, high |
| Stops searching when | low > high ends the loop | Base case low > high returns −1 |
| Keeps the right half by | low = mid + 1; | Calling with mid + 1, high |
| Keeps the left half by | high = mid - 1; | Calling with low, mid - 1 |
The Same Search With Recursive Calls
Predict the output (Figure 3).
public static int binSearch(int[] a, int target, int low, int high)
{
if (low > high)
{
return -1;
}
int mid = (low + high) / 2;
System.out.println("search " + low + " to " + high);
if (a[mid] == target)
{
return mid;
}
if (a[mid] < target)
{
return binSearch(a, target, mid + 1, high);
}
return binSearch(a, target, low, mid - 1);
}
search 0 to 6
search 4 to 6
search 6 to 6
6
- 1Base cases.
low > highmeans nothing is left: −1. A match returnsmid. - 2Recursive calls pass the remaining half: 21 < 57 gives 4 to 6; 42 < 57 gives 6 to 6.
- 3The parameters
lowandhighplay the role of the loop variables in the iterative version.
5When the Value Is Not There
Binary search eliminates half of the remaining elements in each step until the desired value is found or all elements have been eliminated. When every element has been ruled out, low has moved past high: the loop condition low <= high fails, or the recursive base case is reached, and the search returns −1.
At that moment, low is the index where the missing value would belong if it were inserted to keep the data sorted. That observation is not needed to trace a search, but it explains why the range closes exactly between the two neighbors of the missing value.
Eliminating Everything
Search the same array for 20, which is not there.
public static int binarySearch(int[] a, int target)
{
int low = 0;
int high = a.length - 1;
while (low <= high)
{
int mid = (low + high) / 2;
System.out.println("low " + low + ", high " + high + ", mid " + mid);
if (a[mid] == target)
{
return mid;
}
else if (a[mid] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return -1;
}
low 0, high 6, mid 3
low 0, high 2, mid 1
low 2, high 2, mid 2
-1
- 1Step 1. 21 > 20, so
high= 2. - 2Step 2. mid = 1; 8 < 20, so
low= 2. - 3Step 3. mid = 2; 15 < 20, so
low= 3. Nowlow>high: every element has been eliminated, and the method returns −1.
A loop condition of low < high stops while one element remains unchecked, so a target in that position is reported missing. The condition must be low <= high.
6Binary Search Versus Linear Search
Binary search is typically more efficient than linear search. A linear search may examine every element, so 1,000 elements can take 1,000 checks. A binary search halves the remaining range each step, so 1,000 elements take about 10 checks, and 1,000,000 elements about 20. Doubling the amount of data adds only one step.
The trade-off is the requirement of sorted data. For a small or unsorted collection, or one that is searched only once, a linear search is simple and correct. For a large sorted collection searched many times, binary search is far faster.
| Linear search | Binary search | |
|---|---|---|
| Data must be sorted? | No | Yes |
| Where it starts | One end | The middle |
| Eliminated per step | One element | Half of the remaining elements |
| Worst case, 1,000 elements | 1,000 checks | About 10 checks |
| Worst case, 1,000,000 elements | 1,000,000 checks | About 20 checks |
Counting Steps on 1,000 Elements
Count how many elements each search examines to find the last value in a sorted array of 1,000 elements.
public static int linearSteps(int[] a, int target)
{
int steps = 0;
for (int i = 0; i < a.length; i++)
{
steps++;
if (a[i] == target)
{
return steps;
}
}
return steps;
}
public static int binarySteps(int[] a, int target)
{
int steps = 0;
int low = 0;
int high = a.length - 1;
while (low <= high)
{
steps++;
int mid = (low + high) / 2;
if (a[mid] == target)
{
return steps;
}
else if (a[mid] < target)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
return steps;
}
linear 1000, binary 10
- 1The array holds 0, 2, 4, …, 1998, sorted, with 1998 last.
- 2Linear search examines every element before reaching the last one: 1,000.
- 3Binary search halves the range each step: 1,000, 500, 250, … reaches the target in 10 steps.
Watching the Range Shrink
Print how many elements remain before each step of a search for a value larger than all 64 elements.
int[] a = new int[64];
for (int i = 0; i < a.length; i++)
{
a[i] = i;
}
int low = 0;
int high = a.length - 1;
String sizes = "";
while (low <= high)
{
sizes += " " + (high - low + 1);
int mid = (low + high) / 2;
if (a[mid] < 100)
{
low = mid + 1;
}
else
{
high = mid - 1;
}
}
System.out.println(sizes.substring(1));
64 32 16 8 4 2 1
- 1Every step keeps the right half, because every element is less than 100.
- 2The range halves from 64 to 1, then empties, so the search ends after 7 steps (Figure 4).
Four Habits for Binary Search
1. Confirm Sorted Order
Otherwise use linear search.
2. mid Rounds Down
(low + high) / 2 with integer division.
3. Exclude mid
mid + 1 or mid − 1, never mid.
4. low <= high
Stop only when the range is empty.
Data must be in sorted order to use the binary search algorithm. Binary search starts at the middle of a sorted array or ArrayList and eliminates half of the array or ArrayList in each step until the desired value is found or all elements have been eliminated. Binary search is typically more efficient than linear search. The binary search algorithm can be written either iteratively or recursively.