Binary search algorithm
In this post, I will give a brief summary of binary search algorithm, together with some programming problems on this topic.
Algorithm Introduction
- It is a simple recursive searching algorithm.
- Scope of application: in ordered arrays
The pseudo code1 is as follows:
1 |
|
In plain words, it recursively check whether the mid point value is the target, if the target is bigger, check the left half; if the target is smaller, check the right half.
Complexity
- Space complexity Only constant number of variables are used, therefore the space complexity is \(O(1)\).
- Time complexity Because each time after search, half of the array would be 'discarded', therefore the overall complexity is \(O(\log n)\), where \(n\) is the length of the array.
Java Implementation example
1 |
|
1 |
|
Questions
- Leetcode 704 - Binary search - Basic implementation for this algorithm.
- Leetcode 278 - First bad Version - Variation on look-up standards.
- Leetcode 34 - Find First and Last Position of element in Sorted array - Variation on look-up standards and re-use of code.
- Leetcode 33 - Search in rotated sorted array- Variation on the structure of array.
- Leetcode 74 - Search a 2D matrix - Variation on the structure of input array, need to reduce the dimension of input.
- Leetcode 162 - Find peak element - Another realization of binary search algorithm.
- The pseudo code is derived from tutorials point ↩︎
Binary search algorithm
https://delusion4013.github.io/2021/09/11/Binary search algorithm Summary/