Binary search algorithm
Also known as half-interval search, logarithmic search, binary chop.
In computer science, binary 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 to 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.
— Wikipedia
Half-interval search perfectly explains what binary search is about. Binary search usable on ==ordered= array, and we can eliminate half not required results during each iteration until we not find value or processed all data. Very good visualization aviable here: Binary and Linear Search Visualization
Property | Value |
---|---|
Class | Search algorithm |
Data structure | Array |
Worst-case performance | O(log n) |
Best-case performance | O(1) |
Average performance | O(log n) |
Worst-case space complexity | O(1) |
Simple example of binary search algorithm:
1 2 3 4 5 6 7 8 9 10 # I guess < 5
6 7 8 9 10 # answer is higher, I guess < 8
6 7 # answer is lower, I guess < 7
7 # answer is higher, I guess 7 and it's correct!
Code implementation, binary search in Ruby, can you guess some basic concepts?
Results:
Visualize the algorithm, best case scenario:
3 17 22 75 80 202 # I guess 22
lower_bound: 0, upper_bound: 5,
midpoint index: 2, search value: 22
2
"----------------------"
Visualize the algorithm, other case scenario:
3 17 22 75 80 202 # I guess 202
lower_bound: 0, upper_bound: 5,
midpoint index: 2, search value: 202
lower_bound: 3, upper_bound: 5,
midpoint index: 4, search value: 202
lower_bound: 5, upper_bound: 5,
midpoint index: 5, search value: 202
5
Compare with linear search (worst case)
- array items 3 linear search: 3 steps binary search: 2 steps
- array items 7 linear search: 7 steps binary search: 3 steps
- array items 15 linear search: 15 steps binary search: 4 steps …
- array items 100 linear search: 100 steps binary search: 7 steps
- array items 10000 linear search: 10000 steps binary search: ≈13 steps
- array items 1000000 linear search: 1000000 steps binary search: 20 steps
Each lookup step in binary search eliminates half of the elements from the search.
Each time when we double input data for binary-search algorithm, it just takes one more step. For linear search we must double search steps each time.
Difference between and :
N elem. | O(N) | O(log N) |
---|---|---|
8 | 8 | 3 |
16 | 16 | 4 |
32 | 32 | 5 |
64 | 64 | 6 |
128 | 128 | 7 |
256 | 256 | 8 |
512 | 512 | 9 |
1024 | 1024 | 10 |
Binary search efficiency somewhere in between of and (but neither one of them). And its efficiency is ====.
algorithm efficiency is - increases one step each time the data is doubled.