Member-only story
Coding Interview Prep: Binary Search Algorithm
What is Binary Search Algorithm
Binary Search is a searching algorithm for finding an element’s position in a sorted array. In this approach, the element is always searched in the middle of a portion of an array.
Space and Time Complexities
The time complexity of Binary Search is O(logn), where n is the number of elements in the array. It divides the array in half at each step.
The space complexity is O(1) because it uses constant amount of extra space.
Binary search is the most efficient searching algorithm having a run-time complexity of O(logn). It is a searching technique to search an ordered list of data based on the Divide and Conquer technique which repeatedly halves the search space in every iteration.
- Best case time complexity:
O(1)
- Average case time complexity:
O(log n)
- Worst case time complexity:
O(log n)
- Space Complexity:
O(1)
.
How to implement Binary Search
There are 2 ways of implementing binary search algorithm.
- Iterative Method
- Recursive Method