Binary Search
Efficient algorithm for finding an item from a sorted list of items.
Overview
Binary Search is a searching algorithm for finding an element’s position in a sorted array.
The Algorithm
- Compare
xwith the middle element. - If
xmatches with the middle element, we return the mid index. - Else if
xis greater than the mid element, thenxcan only lie in the right half subarray after the mid element. So we recur for the right half. - Else (x is smaller) recur for the left half.
// C++ Implementation
int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
Return to Introduction to Algorithms to review complexity.