Back In the print window choose "Save as PDF" as the destination
NOTE.CS

Search

1+ stars · 2 topics · 28 Nov 2026
1

Binary Search ★★★★★

↑ Index
Algorithm › Search

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++
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++
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.
2

Search Algorithms Comparison ★★☆☆☆

↑ Index
Algorithm › Search
AlgorithmNeeds sorted dataBestAverage / Worst
Linear SearchNoO(1)O(n)
Binary SearchYesO(1)O(log n)
Jump SearchYesO(1)O(√n)
Interpolation SearchYes (uniform values)O(1)O(log log n) / O(n)
Hash lookupNoO(1)O(1) / O(n)