Binary Search¶
In computer science, binary search
, also known as half-interval search
, logarithmic search
, or binary chop
, is a search algorithm that finds the position of a target value within a sorted array. Binary search compares the target value to the middle element of the array. If they are not equal, the half in which the target cannot lie is eliminated and the search continues on the remaining half, again taking the middle element to compare the target value, and repeating this until the target value is found. If the search ends with the remaining half being empty, the target is not in the array.
Binary search can be used to solve a wider range of problems, such as finding the next-smallest or next-largest element in the array relative to the target even if it is absent from the array.
Problems¶
The binary search algorithm solves two kinds of problems:
- to check if a target element is in an array;
- to find the element that is bigger(less) than or equal to a target.
And if you think deeper, you can use the method for second problem to solve first one. That is, to find the element \(\ge\) the target and check if the element found is the target.
Code¶
The main idea of binary search algorithm is to divide the search range into two parts:
- Target must not exit part, which will not be considered in next search process;
- Target may exit part, which will be considered in next search process.
There are two templates for the code, one for left end and one for right:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
Complexity¶
In binary search process, algorithm half the search range every time, so for an array of length \(N\), the worst time complexity is \(O(log(N))\).
The iteration version implementation costs \(O(1)\) space complexity. But for the recursive version, the space complexity is \(O(log(N))\).
Practice¶
There are many kinds of problems, but if the range of problem can be divided into two parts:
- Must not contain the target;
- May contain the target;
it can be solved with binary search.
Binary Search in an Array¶
- 704. Binary Search
- 34. Find First and Last Position of Element in Sorted Array
- 33. Search in Rotated Sorted Array
- 81. Search in Rotated Sorted Array II
- 153. Find Minimum in Rotated Sorted Array
- 154. Find Minimum in Rotated Sorted Array II
- 300. Longest Increasing Subsequence
- 275. H-Index II
- 852. Peak Index in a Mountain Array
- 1095. Find in Mountain Array
- 4. Median of Two Sorted Arrays
- 658. Find K Closest Elements
Binary Search in a Range¶
- 69. Sqrt(x)
- 287. Find the Duplicate Number
- 374. Guess Number Higher or Lower
- 1300. Sum of Mutated Array Closest to Target
Binary Search with Implicit Relations¶
- 410. Split Array Largest Sum
- 875. Koko Eating Bananas
- 1482. Minimum Number of Days to Make m Bouquets
- 1552. Magnetic Force Between Two Balls