Algorithm › Search
Check each element one by one. Works on unsorted data. Time O(n), space O(1).
C++
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
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
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
- Why mid = low + (high - low) / 2?
low + high can overflow int when both are large; this form gives the same value safely.
3
lower_bound and upper_bound
↑ Index
Algorithm › Search
STL binary search helpers on sorted ranges. lower_bound → first element ≥ x. upper_bound → first element > x.
C++
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)