Searching Algorithms: Binary Search
This search algorithm works on the principle of divide and conquer. For this algorithm to work properly, there is a big caveat: the data collection must be sorted.
- Worst and Average Case: O(log n)
- Best Case: O(1)
How Binary Search Works?
Binary search is going to compare the element we are looking for with the middle element of the collection. If there is a match, it will return the index of the middle item. If the middle item is shorter than the item we’re looking for, we forget about the sub-array from the middle to the right, and repeat the operation searching for the sub-array to the left to the middle item.
We continue this process until find the item or until the size of the sub-array reaches 0.
Let’s try to understanding it by looking the algorithm step by step:
// Write a function that accepts a sorted array and a value.// Create a left pointer at the start of the array and a right
pointer at the end. // While the left pointer comes before the right pointer:// Create a pointer in the middle// If you find the value you want, return the index.// If the value is too small, move the left pointer up.// If the value is too large, move the right pointer down.// Return -1 if the value is never found.