The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log n).
Binary Search: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Repeatedly check until the value is found or the interval is empty.
Algo Concept
We basically ignore half of the elements just after one comparison.
- Compare key with the middle element.
- If key matches with the middle element, we return the mid index.
- Else If key is greater than the mid element, then key can only lie in the right half subarray after the mid element. So we recur for the right half.
- Else (key is smaller) recur for the left half.
Please find the code implementation in the first comment and two Unit tests in the second comment.