Binary Search
If we have an array that is sorted, we can use a much more efficient algorithm called a Binary Search. In binary search each time we divide array into two equal half and compare middle element with search element.
Searching Logic
If middle element is equal to search element then we got that element and return that index
If middle element is less than search element we look right part of array
If middle element is greater than search element we look left part of array.
The complexity of Binary Search Technique
Time Complexity: O(1) for the best case. O(log2 n) for average or worst case.
Space Complexity: O(1)
Binary Search - Algorithm
Binary Search - Example
Search for 6 in given array
Example:
Output
Last updated