Show 25 50 100
PDF
4 result(s) in Search Clear

Index

Showing 4 topics
  1. Linear Search
  2. Binary Search
  3. lower_bound and upper_bound
  4. Search Algorithms Comparison
1 Index

Check each element one by one. Works on unsorted data. Time O(n), space O(1).

C++ 5 lines
int linearSearch(int arr[], int n, int key) {
    for (int i = 0; i < n; i++)
        if (arr[i] == key) return i;   // found: return index
    return -1;                         // not found
}
2 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.
3 Index

STL binary search helpers on sorted ranges. lower_bound → first element ≥ x. upper_bound → first element > x.

C++ 5 lines
vector<int> v = {1, 2, 4, 4, 4, 7, 9};
auto lo = lower_bound(v.begin(), v.end(), 4) - v.begin();   // 2
auto hi = upper_bound(v.begin(), v.end(), 4) - v.begin();   // 5
cout << hi - lo;                                            // 3 = count of 4
cout << binary_search(v.begin(), v.end(), 7);               // 1 (true)