Binary Search Basics
How cutting a sorted range in half finds a value, a boundary, or the smallest answer that works, with Java templates.
When you look for page 300 in a thick book, you do not turn the pages one by one. You open it somewhere near the middle, read the page number, and know at once which half to keep. Then you do the same with that half.
Binary search is that habit written as code. It works on anything kept in order, such as a sorted array or a range of possible answers. It finds a value, the place where something starts to be true, or the smallest answer that is good enough, while looking at only a few positions.
Halving a sorted range
Take a sorted array of eight numbers, nums = [2, 4, 7, 7, 7, 9, 11, 14]
Look at the row labelled Step 1. At the start, 11 could be anywhere from index 0 to index 7. The middle of that range is index 3, drawn in orange, and it holds 7.
Since 7 is smaller than 11 and the array is sorted, every number at index 0 to 3 is 7 or less. None of them can be 11, so all four are dropped at once. They turn grey in the row labelled Step 2.
Step 2 repeats the move on the range 4 to 7. Its middle, index 5, holds 9, which is still smaller than 11, so index 4 and 5 go too. In Step 3 the middle of the range 6 to 7 is index 6, and it holds 11.
Three looks were enough, and each one threw away about half of what was left. The name "binary" comes from that split in two at every step.
Notice what made the drop safe: the order. In a shuffled array, seeing 7 at index 3 says nothing about index 0 to 2, and no half could be thrown away.
What halving saves
How much work does the simple way take? Reading nums
The number of looks for halving grows far more slowly. With 8 numbers, the search never needs more than 4 looks. A program that searched every value in a sorted array of 1,000,000 numbers, plus missing values, never needed more than 20 looks.
The reason is that each look halves the range. Starting from 1,000,000 numbers, twenty halvings bring the range down to a single number, because 220 = 1,048,576. In general the count is about log2 n for n numbers, which is written O(log n): the work grows like log n.
Finding one exact value
How do you write the halving down precisely? The code has a fixed shape that carries over from problem to problem, so it is worth learning as a template. The first template keeps two indexes, lohi
- Start with
andlo = 0 , the whole array.hi = n - 1 - While
, the range still holds at least one number. Look at the middle index,lo <= hi .mid - If
is the target, returnnums[mid] .mid - If
is smaller, the target can only be to the right, sonums[mid] .lo = mid + 1 - If it is larger, the target can only be to the left, so
.hi = mid - 1 - When
passeslo , the range is empty and the target is not in the array.hi
Both updates step past midmid
Now search for 8, which is missing. The middle of 0 to 7 is index 3, holding 7, so lohilo
Now lo = 5hi = 4lo
What about 7, which appears three times? The very first look lands on index 3, which holds a 7, and the search returns 3. That is a correct answer to "where is a 7?", but not to "where is the first 7?". That second question needs a different template.
Finding where a condition starts
Many questions are not "where is x?" but "where does something begin?". Where do the 7s start? Where is the first number bigger than 7? Turn each into a yes-or-no question about every index, and look at the answers in a row.
Look at the row labelled "value ≥ 7?". Because the array is sorted, the answers are all "no" first and all "yes" after, and they switch exactly once. The first yes is at index 2, marked in orange. That is where the 7s start.
The row labelled "value > 7?" switches later, at index 5 in teal. Every index from 2 up to 4 holds a 7, so the array has 5 - 2 = 3 copies of 7.
Any test whose answers run "no, no, ..., yes, yes" like these rows is called monotone. The second template finds the first yes for any monotone test. It keeps two indexes, leftrightleftright
- Start with
on the first index andleft one past the last index. The position past the end stands for "no index says yes".right - While
, test the middle indexleft < right .mid - If
says yes, the first yes ismid or earlier, somid . Hereright = mid is kept, because it may be the answer.mid - If
says no, the first yes is after it, somid .left = mid + 1 - When
meetsleft , they point at the first yes.right
On the row "value ≥ 7?", left = 0right = 8rightrightleft
There is no "found it" exit here. The loop always runs until the range closes, so the answer is the first yes even when several positions say yes. If no index says yes, as for "value ≥ 15?", the answer is 8, one past the end.
Searching over possible answers
Binary search does not need an array to look into. It needs a range of candidates and a monotone yes-or-no test. Here is a question with no array to search, built from the same eight numbers.
Treat [2, 4, 7, 7, 7, 9, 11, 14]
The capacity cannot be below 14, or the heaviest package never fits. It never needs to be above 61, the total of all weights, which ships everything in one day. So the answer lies in 14 to 61.
Now ask "does capacity c ship everything in 3 days?". If some capacity works, every bigger one works too, since a bigger truck never needs more days. So the answers run no, ..., no, yes, ..., yes, and the second template applies.
Look at the boxes labelled "the tries, in order". The search first tries 38, the middle of 14 to 61, and it works. Then 26 works too. Then 20 and 23 are too small, and 25 works while 24 does not. So 25 is the smallest capacity, found with six tries.
Check 25 by hand. Day one takes 2, 4, 7 and 7, which is 20, and the next 7 would make 27. Day two takes 7 and 9, which is 16. Day three takes 11 and 14, exactly 25.
The slow way tries 14, 15, 16 and so on until one works. That is 12 tries here, each one a full pass over the packages, and up to 48 if the answer were 61.
The templates in Java
In the program below, the first template is the method exactSearchfirstTrueIntPredicateinti -> nums[i] >= 7
For the packages, daysNeededsmallestCapacityfirstTruedaysNeeded
The program's mainArrays.binarySearch
import java.util.Arrays;
import java.util.function.IntPredicate;
public class BinarySearchBasics {
// Template 1: the index of target in the sorted array nums, or -1 if it is not there.
static int exactSearch(int[] nums, int target) {
int lo = 0;
int hi = nums.length - 1; // target, if present, is in [lo, hi]
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
lo = mid + 1; // target can only be right of mid
} else {
hi = mid - 1; // target can only be left of mid
}
}
return -1;
}
// Template 2: the smallest x in [lo, hi] with ok(x) true, or hi + 1 if there is none.
// ok must answer false, ..., false, true, ..., true as x grows.
static int firstTrue(int lo, int hi, IntPredicate ok) {
int left = lo;
int right = hi + 1; // hi + 1 stands for "never true"
while (left < right) {
int mid = left + (right - left) / 2;
if (ok.test(mid)) {
right = mid; // the first true is mid or earlier
} else {
left = mid + 1; // the first true is after mid
}
}
return left;
}
// How many days it takes to ship the weights in order, at most capacity per day.
static int daysNeeded(int[] weights, int capacity) {
int days = 1;
int load = 0;
for (int w : weights) {
if (load + w > capacity) {
days++;
load = 0;
}
load += w;
}
return days;
}
static int smallestCapacity(int[] weights, int days) {
int heaviest = Arrays.stream(weights).max().getAsInt();
int total = Arrays.stream(weights).sum();
return firstTrue(heaviest, total, c -> daysNeeded(weights, c) <= days);
}
public static void main(String[] args) {
int[] nums = {2, 4, 7, 7, 7, 9, 11, 14};
int n = nums.length;
System.out.println("exactSearch 11: " + exactSearch(nums, 11));
System.out.println("exactSearch 8: " + exactSearch(nums, 8));
System.out.println("exactSearch 7: " + exactSearch(nums, 7));
System.out.println("exactSearch 2: " + exactSearch(nums, 2));
System.out.println("exactSearch 14: " + exactSearch(nums, 14));
System.out.println("empty array: " + exactSearch(new int[0], 5));
int first7 = firstTrue(0, n - 1, i -> nums[i] >= 7);
int after7 = firstTrue(0, n - 1, i -> nums[i] > 7);
System.out.println("first index with value >= 7: " + first7);
System.out.println("first index with value > 7: " + after7);
System.out.println("copies of 7: " + (after7 - first7));
int first8 = firstTrue(0, n - 1, i -> nums[i] >= 8);
int first15 = firstTrue(0, n - 1, i -> nums[i] >= 15);
System.out.println("first index with value >= 8: " + first8);
System.out.println("first index with value >= 15: " + first15);
System.out.println("smallest capacity for 3 days: " + smallestCapacity(nums, 3));
System.out.println("smallest capacity for 1 day: " + smallestCapacity(nums, 1));
System.out.println("smallest capacity for 8 days: " + smallestCapacity(nums, 8));
System.out.println("Arrays.binarySearch 7: " + Arrays.binarySearch(nums, 7));
System.out.println("Arrays.binarySearch 8: " + Arrays.binarySearch(nums, 8));
}
}
Running it prints:
exactSearch 11: 6
exactSearch 8: -1
exactSearch 7: 3
exactSearch 2: 0
exactSearch 14: 7
empty array: -1
first index with value >= 7: 2
first index with value > 7: 5
copies of 7: 3
first index with value >= 8: 5
first index with value >= 15: 8
smallest capacity for 3 days: 25
smallest capacity for 1 day: 61
smallest capacity for 8 days: 14
Arrays.binarySearch 7: 3
Arrays.binarySearch 8: -6
The line exactSearch 7: 3first index with value >= 7: 2copies of 7: 3
The line first index with value >= 8: 5lo
For the packages, 3 days need capacity 25. One day needs 61, the total weight. Eight days need 14, because a truck must still carry the heaviest package alone.
Typical traps
Look at the last two output lines. Arrays.binarySearch(nums, 7)exactSearch
For a missing value it returns a negative number, minus the insertion point minus one. For 8 that is -6, which is -(5) - 1, and 5 is again where 8 would go.
Two more traps hide in how the middle index is worked out and in how the range is updated. The program below shows both:
public class Traps {
// Last index whose value is <= limit, written with lo = mid. maxRounds stops a stuck loop.
static String lastAtMost(int[] nums, int limit, boolean roundUp, int maxRounds) {
int lo = 0;
int hi = nums.length - 1; // assumes nums[0] <= limit
for (int round = 1; lo < hi; round++) {
if (round > maxRounds) {
return "stuck after " + maxRounds + " rounds, lo=" + lo + " hi=" + hi;
}
int mid = roundUp ? lo + (hi - lo + 1) / 2 : lo + (hi - lo) / 2;
if (nums[mid] <= limit) {
lo = mid; // mid is a candidate, keep it
} else {
hi = mid - 1;
}
}
return "answer " + lo;
}
public static void main(String[] args) {
int lo = 1200000000;
int hi = 2000000000;
System.out.println("(lo + hi) / 2 = " + (lo + hi) / 2);
System.out.println("lo + (hi - lo) / 2 = " + (lo + (hi - lo) / 2));
int[] nums = {2, 4, 7, 7, 7, 9, 11, 14};
System.out.println("round down: " + lastAtMost(nums, 7, false, 100));
System.out.println("round up: " + lastAtMost(nums, 7, true, 100));
}
}
Running it prints:
(lo + hi) / 2 = -547483648
lo + (hi - lo) / 2 = 1600000000
round down: stuck after 100 rounds, lo=3 hi=4
round up: answer 4
The first line is the overflow trap. A Java intlohi(lo + hi) / 2
Writing the middle as lo + (hi - lo) / 2
The third line is the stuck-loop trap. The method lastAtMostmidlo = midlo = 3hi = 4mid = 3lo
The guard stopped it after 100 rounds; without one it would loop forever. Rounding the middle up, with lo + (hi - lo + 1) / 2mid
Recognising a binary search problem
How do you spot a problem that fits? Look for one of these signs:
- The input is sorted, and the question is where a value is or where it would go.
- The question asks for the first or last position where something holds, such as the first 7 or the first number bigger than 7.
- The question asks for the smallest or largest value that is "good enough", and a bigger value is always at least as good, like the truck capacity.
- The array is not fully sorted, but one look at the middle still tells you which half to keep, as in an array that was sorted and then rotated.
In each case, write the question as a yes-or-no test and check that its answers switch only once. If they do, the second template fits.
Complexity
Every binary search costs the number of looks times the cost of one look.
- Exact search and boundary search: O(log n) time, because each look halves the range of the n indexes, and O(1) extra space, because only
,lo andhi (ormid andleft ) are kept.right - Searching over answers: O(n log R) time, where R is the number of candidate answers, because each of the roughly log2 R tries runs
over all n packages. Here R is 48, and the search needed 6 tries.daysNeeded
Where to go next
Finding one exact value, as in the first template:
Binary Search is the first template on its own.Search a 2D Matrix treats a sorted grid as one long sorted array.
Finding where a condition starts, as in the second template:
Search Insert Position asks where a missing value would go, like 8 at index 5.Find First and Last Position in Sorted Array uses both boundaries, like the first 7 and the first number past 7.Sqrt(x) searches numbers instead of indexes for the last one whose square fits.
Arrays that are not fully sorted:
Search in Rotated Sorted Array decides which half is still in order before dropping one.Find Peak Element keeps the half that slopes upward, with no sorting at all.
Searching over possible answers:
Capacity To Ship Packages Within D Days is the truck example with any number of days.Koko Eating Bananas searches for the slowest eating speed that still finishes in time.Kth Smallest Element in a Sorted Matrix searches values and counts how many lie below each one.