Searching Algorithms
Every search method buys speed with a condition on the data. Linear search needs nothing and costs O(n). Binary search needs sorted data. Hashing needs extra memory and gives up order. Search trees keep order. The data and the number of queries decide which one fits.
Types of Searching Algorithms
Searching means finding where a value is, or proving it is not there. The searching algorithms that data structures courses teach fall into four types, and each one asks something different of the data.
Linear search asks nothing. Binary search asks for sorted data you can index into. Hashing asks for a hash function and spare memory. A search tree asks for keys that can be compared, kept in order as they change.
So the first question is not which is fastest but which ones the data allows. The second is how many searches will run, because sorting or building an index costs time up front and only pays off when it is reused.
| Method | Set-up | One search | Needs | Range queries |
|---|---|---|---|---|
| Linear search | None | O(n) | Nothing | Scan everything |
| Binary search | Sort: O(n log n) | O(log n) | Sorted array | Yes |
| Hash table | Build: O(n) | O(1) average | Hash function, memory | No |
| Balanced search tree | Build: O(n log n) | O(log n) | Comparable keys | Yes |
- Pick from what the data allows, then by how many searches will run
Linear Search
Look at each element from one end until the target turns up or the data runs out. A hit at position k costs k comparisons; a miss costs all n, because the only way to prove a value is absent is to look at everything. That is O(n).
It is the only option for unsorted data you search once, for linked lists, and for streams you cannot revisit. It is also often the fastest choice on small arrays, up to a few dozen elements, because a straight scan reads memory in order and has no hard-to-predict branches.
A sentinel version copies the target into an extra slot at the end, so the loop never has to check whether it has run out of elements: one test per step instead of two.
- Works on any collection, in any order
- Hit: up to n comparisons; miss: always n
Linear Search vs Binary Search
Binary search compares the target with the middle of a sorted range and throws away the half that cannot hold it. Each comparison halves the range, so about 20 comparisons cover a million elements and 30 cover a billion: O(log n).
The price is the precondition. The array must be sorted, and it must allow jumping straight to the middle, which rules out linked lists. Run it on unsorted data and it does not slow down; it gives wrong answers, because it discards halves that hold the target.
So linear search vs binary search comes down to how many searches there are. Sorting costs about n log₂ n comparisons. For a single search on unsorted data a scan is cheaper. Once the number of searches passes roughly log₂ n, sorting once and searching many times wins. Bounds, invariants and the classic off-by-one bugs are covered in the binary search lesson.
- Binary search on unsorted data is wrong, not just slow
- Sort first only when the searches repay the n log n set-up
- Practice: Search Insert Position, Find First and Last Position of Element in Sorted Array
Terms, operations, and practical uses
Search vocabulary
- TargetThe value or condition being located.
- Search intervalThe region that is still capable of containing the answer.
- Monotonic predicateA yes/no condition that changes direction at most once across an ordered domain.
Binary-search boundaries
- Lower boundThe first position whose value is at least the target.
- Upper boundThe first position whose value is greater than the target.
- MidpointThe inspected position that proves which portion can be discarded.
Choose the right search
- Linear searchNeeds no preprocessing and works on unsorted data.
- Binary searchHalves a sorted range each step for
O(log n)lookup. - Hash lookupProvides expected constant-time membership by maintaining an auxiliary index.
- Binary search treeKeeps keys ordered, so range queries and successors stay cheap.
- Sorting firstOrdering once pays off when a collection is searched many times.
- Answer-space searchBinary-searches possible results when feasibility changes monotonically.
Code in Python, C++ and Java
def binary_search(values, target):
left, right = 0, len(values) - 1
while left <= right:
middle = left + (right - left) // 2
if values[middle] == target:
return middle
if values[middle] < target:
left = middle + 1
else:
right = middle - 1
return -1
print('index', binary_search([2, 5, 8, 12, 16, 21, 29], 16))#include <iostream>
#include <vector>
using namespace std;
int binarySearch(const vector<int>& values, int target) {
int left = 0, right = (int)values.size() - 1;
while (left <= right) {
int middle = left + (right - left) / 2; // avoids overflow
if (values[middle] == target) return middle;
if (values[middle] < target) left = middle + 1;
else right = middle - 1;
}
return -1;
}
int main() {
vector<int> values = {2, 5, 8, 12, 16, 21, 29};
cout << "index " << binarySearch(values, 16) << '\n';
}class Main {
static int binarySearch(int[] values, int target) {
int left = 0, right = values.length - 1;
while (left <= right) {
int middle = left + (right - left) / 2; // avoids overflow
if (values[middle] == target) return middle;
if (values[middle] < target) left = middle + 1;
else right = middle - 1;
}
return -1;
}
public static void main(String[] args) {
int[] values = {2, 5, 8, 12, 16, 21, 29};
System.out.println("index " + binarySearch(values, 16));
}
}Step through it
Running on keys [29, 5, 16, 2, 21, 8, 12]; targets 16 and 17; range 8 to 16
Hash Lookup
A hash table does not search at all in the usual sense. It computes where a key should be: hash the key, reduce it to a bucket number, look in that bucket. With a sensible load factor a bucket holds about one key, so a lookup is O(1) on average however many keys there are.
For "have I seen this before?" nothing is faster, which is why so many nested-loop O(n²) solutions become one O(n) pass with a set. See Two Sum and Contains Duplicate.
Two costs come with it. The worst case is O(n) when many keys land in one bucket, and an attacker who knows the hash function can force that; this is why Python randomises its string hashes on every run. And a hash table scatters keys on purpose, so it cannot answer "smallest key", "keys between 8 and 16" or "next key after 12" without looking at every entry.
- O(1) average, O(n) worst case
- Exact-match lookups only: no order, no ranges
Search Trees
A binary search tree keeps every key in order: smaller to the left, larger to the right. A search walks down from the root, one comparison per level. Balanced versions such as AVL and red-black trees keep the height near log₂ n, so every search, insert and delete is O(log n) guaranteed.
Order is what the tree is for. It answers range queries (go down to the lower bound, then walk in order), floor and ceiling (the nearest key below or above a value), smallest and largest, and sorted iteration. That is why both std::map and std::unordered_map, or TreeMap and HashMap, exist side by side.
Without balancing, a tree built from sorted input becomes a chain and a search costs O(n). On disk, B-trees put hundreds of keys in each node so a lookup reads only three or four blocks, which is why database indexes use them.
- Balanced trees: O(log n) guaranteed, order kept
- Range, floor, ceiling and sorted iteration come free
Choosing a Searching Algorithm
- One search over unsorted data: linear search
- A few dozen elements or fewer: linear search is often fastest anyway
- Data that never changes and is searched many times: sort once, then binary search
- Many exact-match lookups, with inserts and deletes: hash table
- Any question about order or ranges, with inserts and deletes: balanced search tree
- Data on disk: B-tree or B+ tree index
The number of searches decides whether set-up is worth paying for; the kind of question decides what to build.
Other array searches refine binary search for special cases: jump search checks every √n-th element and then scans, interpolation search guesses the position from the value and averages O(log log n) on evenly spread data, exponential search doubles a bound first when the size is unknown, and ternary search finds the peak of a function that rises then falls.
- Count the searches before paying for set-up
- Order questions need a sorted array or a tree; exact matches suit a hash table