Binary Search
Works for a sorted sequence of anything.
Idea is to reduce the search space repeatedly until we reach to the final element or search space becomes exhausted.
// Iterative Approach
int left = 0 ,right = n -1;
while(left<=right)
int mid = (left + right)/2;
if(arr[mid] == k)
return ans
else if(arr[mid] > k)
right = mid - 1;
else
left = mid + 1;
//Recursive Approach
BinarySearch(arr,l,r){
if(l>r)
return -1;
mid = l + (r-l)/2;
if(arr[mid]>k)
BinarySearch(arr,l,mid -1)
else-if(arr[mid]<k)
BinarySearch(arr,mid+1,r)
else
return mid;
Complexity analysis:
TIme : O(long)
Edge cases: When right == -1 or left == n