Show 25 50 100
PDF
1 result(s) in Search with 5+ ★ Clear

Index

Showing 1 topic
  1. Binary Search
1 Index

Works only on a sorted array. Compare with the middle element and discard half of the range each time. Time O(log n), space O(1) (iterative).

Searching 23 takes only 3 steps for 10 elements

Searching 23 takes only 3 steps for 10 elements

Iterative C++ 10 lines
int binarySearch(int arr[], int n, int key) {
    int low = 0, high = n - 1;
    while (low <= high) {
        int mid = low + (high - low) / 2;   // avoids overflow of (low + high)
        if (arr[mid] == key) return mid;
        if (arr[mid] < key) low = mid + 1;
        else high = mid - 1;
    }
    return -1;
}
Recursive (O(log n) stack space) C++ 7 lines
int binarySearch(int arr[], int low, int high, int key) {
    if (low > high) return -1;
    int mid = low + (high - low) / 2;
    if (arr[mid] == key) return mid;
    if (arr[mid] < key) return binarySearch(arr, mid + 1, high, key);
    return binarySearch(arr, low, mid - 1, key);
}

Q & A

  1. Why mid = low + (high - low) / 2?
    low + high can overflow int when both are large; this form gives the same value safely.