10.1 Binary search¶
Binary search is an efficient search algorithm based on divide and conquer. It uses the sorted order of the data to halve the search range at each iteration until it finds the target or the interval is empty.
Question
Given an array nums of length \(n\) with distinct elements in ascending order, find and return the index of target. If the array does not contain the target, return \(-1\). Figure 10-1 shows an example.
Figure 10-1 Sample data for binary search
Description of Figure 10-1: Sample input for binary search
A bar chart and a row of array cells show the same sorted array and search target.
Given the strictly increasing array nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35], with indices 0 through 9, find target = 6.
The upper panel, “Represent the array as a bar chart,” shows ten vertical bars increasing in height from left to right. Each bar has its element value at the top. The indices 0 through 9 appear below the bars under the label “Index.” The lower panel shows the same array as ten adjacent cells in a row. A double-headed arrow connects the panels to show that the bar chart and the one-dimensional array represent exactly the same data.
Both the bar chart and the array cells highlight the value 6 at index 2 in teal. To its left, indices 0 and 1 hold the smaller values 1 and 3. To its right, indices 3 through 9 hold the larger values 8, 12, 15, 23, 26, 31, and 35, respectively. This figure introduces the input and target before binary search begins halving the interval.
A successful search should return index 2, where the target appears.
As Figure 10-2 shows, initialize pointers \(i = 0\) and \(j = n - 1\) at the first and last elements of the array. They define the search interval \([0, n - 1]\). The square brackets denote a closed interval, which includes both endpoints.
Repeat the following two steps.
- Compute the midpoint index \(m = \lfloor {(i + j) / 2} \rfloor\), where \(\lfloor \: \rfloor\) means rounding down.
- Compare
nums[m]withtarget. There are three cases.- If
nums[m] < target, any match fortargetmust be in \([m + 1, j]\), so set \(i = m + 1\). - If
nums[m] > target, any match fortargetmust be in \([i, m - 1]\), so set \(j = m - 1\). - If
nums[m] = target, we have foundtarget. Return index \(m\).
- If
If the array does not contain the target, the search interval eventually becomes empty. Return \(-1\).
Figure 10-2 Steps of binary search
Description of Figure 10-2: Binary search
Search an ascending array for 6. In each iteration, compare the midpoint element with the target and rule out the half that cannot contain it.
The input is an ascending array of 10 distinct elements at indices 0 through 9. The search target is 6 (target = 6). The input table gives the value at each index.
Pointers i and j mark the left and right boundaries of the current closed search interval [i, j], which includes both endpoints. The midpoint index m is (i + j) / 2 rounded down. Each iteration first computes m, then compares nums[m] with the target.
The seven frames show initialization followed by three comparisons. Each iteration has one frame for computing the midpoint and another for narrowing the interval or finding a match. A dashed outline marks the current search interval.
| Index | Element value |
|---|---|
| 0 | 1 |
| 1 | 3 |
| 2 | 6 |
| 3 | 8 |
| 4 | 12 |
| 5 | 15 |
| 6 | 23 |
| 7 | 26 |
| 8 | 31 |
| 9 | 35 |
Initialize the search interval
Set i = 0 and j = 9. The closed search interval [0, 9] covers all 10 elements, with 1 at the left endpoint and 35 at the right. The midpoint m has yet to be computed.
Iteration 1: Compute midpoint m = 4
In the closed interval [0, 9], i = 0 and j = 9. Rounding m = (0 + 9) / 2 down gives 4, the index of 12. Next, compare 12 with the target, 6.
Iteration 1: 12 is greater than 6, so move the right boundary to 3
In the original interval [0, 9], the value 12 at m = 4 is greater than the target, 6. Since the array is in ascending order, the target cannot be at index 4 or to its right. Set j = m - 1 = 3. Now i = 0 and j = 3. The interval [0, 3] contains [1, 3, 6, 8]. The old midpoint pointer m still points outside the interval to index 4 (value 12) until the midpoint is recomputed.
Iteration 2: Compute midpoint m = 1
In the closed interval [0, 3], i = 0 and j = 3. Rounding m = (0 + 3) / 2 down gives 1, the index of 3. Next, compare 3 with the target, 6.
Iteration 2: 3 is less than 6, so move the left boundary to 2
In the original interval [0, 3], the value 3 at m = 1 is less than the target, 6. Since the array is in ascending order, the target cannot be at index 1 or to its left. Set i = m + 1 = 2. Now i = 2 and j = 3. The interval [2, 3] contains [6, 8]. The old midpoint pointer m still points outside the interval to index 1 (value 3) until the midpoint is recomputed.
Iteration 3: Compute midpoint m = 2
In the closed interval [2, 3], i = 2 and j = 3. Rounding m = (2 + 3) / 2 down gives 2. The midpoint now coincides with the left boundary i and points to 6. Next, compare this value with the target, 6.
Iteration 3: Target found, return index 2
The value 6 at m = 2 equals the target, 6, so the search ends. The final frame shows only the midpoint pointer m at index 2. The boundary pointers i and j and the dashed outline are hidden.
The midpoint values are 12, 3, and 6, in that order. The third comparison finds 6 and returns its index, 2.
Since \(i\) and \(j\) both have type int, their sum \(i + j\) may exceed the range of int. To avoid integer overflow, we usually compute the midpoint as \(m = \lfloor {i + (j - i) / 2} \rfloor\).
The following code implements the search:
def binary_search(nums: list[int], target: int) -> int:
"""Binary search on a closed interval"""
# Initialize the closed interval [0, n-1] with i at the first element and j at the last
i, j = 0, len(nums) - 1
# Stop when the search interval is empty (i > j)
while i <= j:
# Python integers can grow as large as memory allows, so overflow is not a concern here
m = (i + j) // 2 # Compute the midpoint index m
if nums[m] < target:
i = m + 1 # Any match must lie in [m+1, j]
elif nums[m] > target:
j = m - 1 # Any match must lie in [i, m-1]
else:
return m # Found the target. Return its index
return -1 # Target not found. Return -1
/* Binary search on a closed interval */
int binarySearch(vector<int> &nums, int target) {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
int i = 0, j = nums.size() - 1;
// Stop when the search interval is empty (i > j)
while (i <= j) {
int m = i + (j - i) / 2; // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j]
i = m + 1;
else if (nums[m] > target) // Any match must lie in [i, m-1]
j = m - 1;
else // Found the target. Return its index
return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a closed interval */
int binarySearch(int[] nums, int target) {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
int i = 0, j = nums.length - 1;
// Stop when the search interval is empty (i > j)
while (i <= j) {
int m = i + (j - i) / 2; // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j]
i = m + 1;
else if (nums[m] > target) // Any match must lie in [i, m-1]
j = m - 1;
else // Found the target. Return its index
return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a closed interval */
int BinarySearch(int[] nums, int target) {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
int i = 0, j = nums.Length - 1;
// Stop when the search interval is empty (i > j)
while (i <= j) {
int m = i + (j - i) / 2; // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j]
i = m + 1;
else if (nums[m] > target) // Any match must lie in [i, m-1]
j = m - 1;
else // Found the target. Return its index
return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a closed interval */
func binarySearch(nums []int, target int) int {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
i, j := 0, len(nums)-1
// Stop when the search interval is empty (i > j)
for i <= j {
m := i + (j-i)/2 // Compute the midpoint index m
if nums[m] < target { // Any match must lie in [m+1, j]
i = m + 1
} else if nums[m] > target { // Any match must lie in [i, m-1]
j = m - 1
} else { // Found the target. Return its index
return m
}
}
// Target not found. Return -1
return -1
}
/* Binary search on a closed interval */
func binarySearch(nums: [Int], target: Int) -> Int {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
var i = nums.startIndex
var j = nums.endIndex - 1
// Stop when the search interval is empty (i > j)
while i <= j {
let m = i + (j - i) / 2 // Compute the midpoint index m
if nums[m] < target { // Any match must lie in [m+1, j]
i = m + 1
} else if nums[m] > target { // Any match must lie in [i, m-1]
j = m - 1
} else { // Found the target. Return its index
return m
}
}
// Target not found. Return -1
return -1
}
/* Binary search on a closed interval */
function binarySearch(nums, target) {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
let i = 0,
j = nums.length - 1;
// Stop when the search interval is empty (i > j)
while (i <= j) {
// Compute the midpoint index m, rounding down with parseInt()
const m = parseInt(i + (j - i) / 2);
if (nums[m] < target)
// Any match must lie in [m+1, j]
i = m + 1;
else if (nums[m] > target)
// Any match must lie in [i, m-1]
j = m - 1;
else return m; // Found the target. Return its index
}
// Target not found. Return -1
return -1;
}
/* Binary search on a closed interval */
function binarySearch(nums: number[], target: number): number {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
let i = 0,
j = nums.length - 1;
// Stop when the search interval is empty (i > j)
while (i <= j) {
// Compute the midpoint index m
const m = Math.floor(i + (j - i) / 2);
if (nums[m] < target) {
// Any match must lie in [m+1, j]
i = m + 1;
} else if (nums[m] > target) {
// Any match must lie in [i, m-1]
j = m - 1;
} else {
// Found the target. Return its index
return m;
}
}
return -1; // Target not found. Return -1
}
/* Binary search on a closed interval */
int binarySearch(List<int> nums, int target) {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
int i = 0, j = nums.length - 1;
// Stop when the search interval is empty (i > j)
while (i <= j) {
int m = i + (j - i) ~/ 2; // Compute the midpoint index m
if (nums[m] < target) {
// Any match must lie in [m+1, j]
i = m + 1;
} else if (nums[m] > target) {
// Any match must lie in [i, m-1]
j = m - 1;
} else {
// Found the target. Return its index
return m;
}
}
// Target not found. Return -1
return -1;
}
/* Binary search on a closed interval */
fn binary_search(nums: &[i32], target: i32) -> i32 {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
let mut i = 0;
let mut j = nums.len() as i32 - 1;
// Stop when the search interval is empty (i > j)
while i <= j {
let m = i + (j - i) / 2; // Compute the midpoint index m
if nums[m as usize] < target {
// Any match must lie in [m+1, j]
i = m + 1;
} else if nums[m as usize] > target {
// Any match must lie in [i, m-1]
j = m - 1;
} else {
// Found the target. Return its index
return m;
}
}
// Target not found. Return -1
return -1;
}
/* Binary search on a closed interval */
int binarySearch(int *nums, int len, int target) {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
int i = 0, j = len - 1;
// Stop when the search interval is empty (i > j)
while (i <= j) {
int m = i + (j - i) / 2; // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j]
i = m + 1;
else if (nums[m] > target) // Any match must lie in [i, m-1]
j = m - 1;
else // Found the target. Return its index
return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a closed interval */
fun binarySearch(nums: IntArray, target: Int): Int {
// Initialize the closed interval [0, n-1] with i at the first element and j at the last
var i = 0
var j = nums.size - 1
// Stop when the search interval is empty (i > j)
while (i <= j) {
val m = i + (j - i) / 2 // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j]
i = m + 1
else if (nums[m] > target) // Any match must lie in [i, m-1]
j = m - 1
else // Found the target. Return its index
return m
}
// Target not found. Return -1
return -1
}
### Binary search on a closed interval ###
def binary_search(nums, target)
# Initialize the closed interval [0, n-1] with i at the first element and j at the last
i, j = 0, nums.length - 1
# Stop when the search interval is empty (i > j)
while i <= j
# Ruby integers can grow as large as memory allows, so overflow is not a concern here
m = (i + j) / 2 # Compute the midpoint index m
if nums[m] < target
i = m + 1 # Any match must lie in [m+1, j]
elsif nums[m] > target
j = m - 1 # Any match must lie in [i, m-1]
else
return m # Found the target. Return its index
end
end
-1 # Target not found. Return -1
end
Visualize execution
Time complexity: \(O(\log n)\). Each iteration halves the interval, so the loop takes \(\log_2 n\) iterations.
Space complexity: \(O(1)\). The pointers \(i\) and \(j\) take up a constant amount of space.
10.1.1 Representing the search interval¶
Another common convention is a left-closed, right-open interval such as \([0, n)\). It includes its left endpoint and excludes its right endpoint. With this convention, \([i, j)\) is empty when \(i = j\).
We can use this convention to implement binary search with the same behavior:
def binary_search_lcro(nums: list[int], target: int) -> int:
"""Binary search on a left-closed, right-open interval"""
# Initialize [0, n) with i at the first element and j one past the last
i, j = 0, len(nums)
# Stop when the search interval is empty (i = j)
while i < j:
m = (i + j) // 2 # Compute the midpoint index m
if nums[m] < target:
i = m + 1 # Any match must lie in [m+1, j)
elif nums[m] > target:
j = m # Any match must lie in [i, m)
else:
return m # Found the target. Return its index
return -1 # Target not found. Return -1
/* Binary search on a left-closed, right-open interval */
int binarySearchLCRO(vector<int> &nums, int target) {
// Initialize [0, n) with i at the first element and j one past the last
int i = 0, j = nums.size();
// Stop when the search interval is empty (i = j)
while (i < j) {
int m = i + (j - i) / 2; // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j)
i = m + 1;
else if (nums[m] > target) // Any match must lie in [i, m)
j = m;
else // Found the target. Return its index
return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a left-closed, right-open interval */
int binarySearchLCRO(int[] nums, int target) {
// Initialize [0, n) with i at the first element and j one past the last
int i = 0, j = nums.length;
// Stop when the search interval is empty (i = j)
while (i < j) {
int m = i + (j - i) / 2; // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j)
i = m + 1;
else if (nums[m] > target) // Any match must lie in [i, m)
j = m;
else // Found the target. Return its index
return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a left-closed, right-open interval */
int BinarySearchLCRO(int[] nums, int target) {
// Initialize [0, n) with i at the first element and j one past the last
int i = 0, j = nums.Length;
// Stop when the search interval is empty (i = j)
while (i < j) {
int m = i + (j - i) / 2; // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j)
i = m + 1;
else if (nums[m] > target) // Any match must lie in [i, m)
j = m;
else // Found the target. Return its index
return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a left-closed, right-open interval */
func binarySearchLCRO(nums []int, target int) int {
// Initialize [0, n) with i at the first element and j one past the last
i, j := 0, len(nums)
// Stop when the search interval is empty (i = j)
for i < j {
m := i + (j-i)/2 // Compute the midpoint index m
if nums[m] < target { // Any match must lie in [m+1, j)
i = m + 1
} else if nums[m] > target { // Any match must lie in [i, m)
j = m
} else { // Found the target. Return its index
return m
}
}
// Target not found. Return -1
return -1
}
/* Binary search on a left-closed, right-open interval */
func binarySearchLCRO(nums: [Int], target: Int) -> Int {
// Initialize [0, n) with i at the first element and j one past the last
var i = nums.startIndex
var j = nums.endIndex
// Stop when the search interval is empty (i = j)
while i < j {
let m = i + (j - i) / 2 // Compute the midpoint index m
if nums[m] < target { // Any match must lie in [m+1, j)
i = m + 1
} else if nums[m] > target { // Any match must lie in [i, m)
j = m
} else { // Found the target. Return its index
return m
}
}
// Target not found. Return -1
return -1
}
/* Binary search on a left-closed, right-open interval */
function binarySearchLCRO(nums, target) {
// Initialize [0, n) with i at the first element and j one past the last
let i = 0,
j = nums.length;
// Stop when the search interval is empty (i = j)
while (i < j) {
// Compute the midpoint index m, rounding down with parseInt()
const m = parseInt(i + (j - i) / 2);
if (nums[m] < target)
// Any match must lie in [m+1, j)
i = m + 1;
else if (nums[m] > target)
// Any match must lie in [i, m)
j = m;
// Found the target. Return its index
else return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a left-closed, right-open interval */
function binarySearchLCRO(nums: number[], target: number): number {
// Initialize [0, n) with i at the first element and j one past the last
let i = 0,
j = nums.length;
// Stop when the search interval is empty (i = j)
while (i < j) {
// Compute the midpoint index m
const m = Math.floor(i + (j - i) / 2);
if (nums[m] < target) {
// Any match must lie in [m+1, j)
i = m + 1;
} else if (nums[m] > target) {
// Any match must lie in [i, m)
j = m;
} else {
// Found the target. Return its index
return m;
}
}
return -1; // Target not found. Return -1
}
/* Binary search on a left-closed, right-open interval */
int binarySearchLCRO(List<int> nums, int target) {
// Initialize [0, n) with i at the first element and j one past the last
int i = 0, j = nums.length;
// Stop when the search interval is empty (i = j)
while (i < j) {
int m = i + (j - i) ~/ 2; // Compute the midpoint index m
if (nums[m] < target) {
// Any match must lie in [m+1, j)
i = m + 1;
} else if (nums[m] > target) {
// Any match must lie in [i, m)
j = m;
} else {
// Found the target. Return its index
return m;
}
}
// Target not found. Return -1
return -1;
}
/* Binary search on a left-closed, right-open interval */
fn binary_search_lcro(nums: &[i32], target: i32) -> i32 {
// Initialize [0, n) with i at the first element and j one past the last
let mut i = 0;
let mut j = nums.len() as i32;
// Stop when the search interval is empty (i = j)
while i < j {
let m = i + (j - i) / 2; // Compute the midpoint index m
if nums[m as usize] < target {
// Any match must lie in [m+1, j)
i = m + 1;
} else if nums[m as usize] > target {
// Any match must lie in [i, m)
j = m;
} else {
// Found the target. Return its index
return m;
}
}
// Target not found. Return -1
return -1;
}
/* Binary search on a left-closed, right-open interval */
int binarySearchLCRO(int *nums, int len, int target) {
// Initialize [0, n) with i at the first element and j one past the last
int i = 0, j = len;
// Stop when the search interval is empty (i = j)
while (i < j) {
int m = i + (j - i) / 2; // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j)
i = m + 1;
else if (nums[m] > target) // Any match must lie in [i, m)
j = m;
else // Found the target. Return its index
return m;
}
// Target not found. Return -1
return -1;
}
/* Binary search on a left-closed, right-open interval */
fun binarySearchLCRO(nums: IntArray, target: Int): Int {
// Initialize [0, n) with i at the first element and j one past the last
var i = 0
var j = nums.size
// Stop when the search interval is empty (i = j)
while (i < j) {
val m = i + (j - i) / 2 // Compute the midpoint index m
if (nums[m] < target) // Any match must lie in [m+1, j)
i = m + 1
else if (nums[m] > target) // Any match must lie in [i, m)
j = m
else // Found the target. Return its index
return m
}
// Target not found. Return -1
return -1
}
### Binary search on a left-closed, right-open interval ###
def binary_search_lcro(nums, target)
# Initialize [0, n) with i at the first element and j one past the last
i, j = 0, nums.length
# Stop when the search interval is empty (i = j)
while i < j
# Compute the midpoint index m
m = (i + j) / 2
if nums[m] < target
i = m + 1 # Any match must lie in [m+1, j)
elsif nums[m] > target
j = m # Any match must lie in [i, m)
else
return m # Found the target. Return its index
end
end
-1 # Target not found. Return -1
end
Visualize execution
As Figure 10-3 shows, the choice of interval changes how we initialize binary search, test the loop condition, and narrow the interval.
A closed interval includes both endpoints, so the updates that narrow the interval using \(i\) and \(j\) are symmetric. This makes mistakes less likely, which is why we generally recommend the closed-interval convention.
Figure 10-3 Two ways to define the search interval
Description of Figure 10-3: Interval conventions in binary search
Whether the search interval includes its right endpoint j determines how to initialize j, when to stop the loop, and how to update j when moving the right boundary to the left.
The ascending array has n = 10 elements at indices 0 through 9. Pointers i and j mark the left and right boundaries of the current search interval, and m is the current midpoint index. The bar heights show only that the values increase. No specific element values are labeled.
The dashed blue box in each panel encloses ten elements. In the left panel, the closed interval [i, j] includes its right endpoint j, which points to the last bar. In the right panel, the half-open interval [i, j) excludes its right endpoint j, which points just past the end of the array. For n = 10, the initialization formulas give j = 9 on the left and j = 10 on the right.
When i = j, the closed interval still contains one element to check, while the half-open interval is empty. When shrinking the interval to the left, the closed interval includes its right endpoint, so set j = m − 1 to exclude m. The half-open interval already excludes its right endpoint, so set j = m. The table gives the four rules shown and adds the while condition, the logical opposite of the stopping condition.
| Rule | Closed interval [i, j] | Half-open interval [i, j), including i and excluding j |
|---|---|---|
| Initialization | i = 0, j = n − 1 | i = 0, j = n |
| Loop termination (with the loop condition in parentheses) | i > j (while i ≤ j) | i ≥ j (while i < j) |
| Middle value below target | i = m + 1 | i = m + 1 |
| Middle value above target | j = m − 1 | j = m |
Each convention requires a matching initialization, loop condition, and pair of boundary updates. The updates at the two ends of a closed interval are symmetric.
10.1.2 Advantages and limitations¶
Binary search is efficient in both time and space.
- Binary search is fast. Its logarithmic time complexity gives it a substantial advantage on large datasets. For example, with \(n = 2^{20}\) elements, linear search takes \(2^{20} = 1048576\) iterations, while binary search needs only \(\log_2 2^{20} = 20\).
- Binary search needs no additional storage for the data. It uses less space than methods that require an auxiliary structure, such as hash lookup.
Binary search has several limitations to consider.
- Binary search requires sorted data. If the input is unsorted, sorting it just to run a search costs more than it saves. Sorting algorithms typically take \(O(n \log n)\) time, more than either linear or binary search. Frequent insertions are also expensive: keeping the array sorted requires inserting each element at a particular position, which takes \(O(n)\) time.
- Binary search applies only to arrays. It needs to jump between nonconsecutive elements. Those jumps are inefficient in a linked list, making binary search a poor fit for linked lists and structures built on them.
- Linear search performs better on small inputs. Each iteration of linear search requires just one test. An iteration of binary search requires one addition, one division, one to three tests, and one more addition or subtraction, for a total of four to six basic operations. When \(n\) is small, linear search is therefore faster.