Binary Search

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

  1. Compare x with the middle element.
  2. If x matches with the middle element, we return the mid index.
  3. Else if x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.
  4. 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.

Sponsored
Mobile Ad Banner