Sequential and binary search
Binary search finds a value in a sorted array in O(log n) by comparing with the middle and dropping half, written with lo <= hi, mid + 1 and mid - 1; the STL has find for sequential search and binary_search.
Chapter 0 met binary search when it explained log n: look in the middle, throw half away. This chapter is all about searching, and starts by writing the two basic kinds right and counting them properly: sequential search, from start to end, and binary search, for sorted arrays only. The code uses vector<int> throughout and passes it as const vector<int>&: by reference, so the whole array isn't copied.
Sequential search and the sentinel
Sequential search is the plainest: compare one by one from the start. Each round actually checks two things: "found it yet?" and "reached the end yet?".
1for (int i = 0; i < n; i++) // check 1: i < n2 if (a[i] == x) return i; // check 2: a[i] == x3return -1;
A sentinel puts the x being looked for at the front of the array first, in a[0] (the real values are stored from index 1), then searches from the back. Since a[0] is certainly x, the loop certainly stops, and "reached the end yet?" needn't be asked:
i1a[0] = x; // the sentinel2int i = n;3while (a[i] != x) i--; // just one check left4return i; // 0 means not found
One comparison fewer each round. For large n that makes sequential search nearly twice as fast, which is why textbooks write it this way.
The average search length (ASL) is the measure of how fast a search is: how many comparisons finding each element takes, averaged. Sequential search takes i comparisons to find the i-th, so with all n equally likely to be looked for, ASL = (1 + 2 + … + n) / n = (n + 1) / 2.
9 elements, each as likely to be looked for as any other. On average, how many comparisons does a successful sequential search take (ASL)?
Sequential search with a sentinel
✓The data is in a[1..n], with a[0] kept for the sentinel (n = a.size() − 1). Finish search: put the sentinel in place, search from the back, return the index (0 for not found). a gets changed, so it's passed as vector<int>&, without const.
3 5 0
1#include <iostream>2#include <vector>3using namespace std;4 5int search(vector<int>& a, int x) {6 int n = (int)a.size() - 1;7 // a[0] = x; i starts at n, i-- while a[i] != x; return i8 return 0;9}10 11int main() {12 vector<int> a = {0, 34, 7, 21, 90, 7, 15, 62}; // a[1..7]13 cout << search(a, 21) << " " << search(a, 7) << " " << search(a, 50) << endl;14 return 0;15}
Binary search: why each line is the way it is
Binary search is short but easy to get wrong, because every line has to fit the others. The safest way is to settle one sentence first: if x is there at all, it's in a[lo..hi] (both ends included). Every other line is there to keep that sentence true:
- At first the whole array is possible, so
lo = 0, hi = n − 1. - While a[lo..hi] still holds something (
lo <= hi; when they're equal, one is left), carry on. a[mid] < x: mid and everything left of it are too small, the possible range becomes a[mid + 1..hi], solo = mid + 1.a[mid] > x: likewise,hi = mid − 1.
lo↑hi↑mid1int lo = 0, hi = (int)a.size() - 1;2while (lo <= hi) {3 int mid = lo + (hi - lo) / 2;4 if (a[mid] == x) return mid;5 if (a[mid] < x) lo = mid + 1;6 else hi = mid - 1;7}8return -1;
mid = (lo + hi) / 2 overflows to a negative number when lo + hi passes the int limit (about 2.1 billion), and the index goes wrong. The safe form is mid = lo + (hi − lo) / 2; Java's standard library once had to fix exactly this bug. a.size() is an unsigned size_t, and for an empty vector a.size() - 1 becomes a huge number, so cast it to int before subtracting.
Binary search for 79 in 3 8 15 23 42 57 61 79 88. Which indexes does it look at as mid, in order?
Pick what goes in the mid line so the binary search is right and can't overflow. Searching for 42, 3 and 50, the program should print 4 0 -1.
1#include <iostream>2#include <vector>3using namespace std;4 5int bs(const vector<int>& a, int x) {6 int lo = 0, hi = (int)a.size() - 1;7 while (lo <= hi) {8 int mid = lo + ;9 if (a[mid] == x) return mid;10 if (a[mid] < x) lo = mid + 1;11 else hi = mid - 1;12 }13 return -1;14}15 16int main() {17 vector<int> a = {3, 8, 15, 23, 42, 57, 61, 79, 88};18 cout << bs(a, 42) << " " << bs(a, 3) << " " << bs(a, 50) << endl;19 return 0;20}
hi - lo can't overflow. lo + (hi + lo) / 2 adds lo one time too many, and so does lo + hi / 2: once lo is big, mid runs past hi, even off the end of the array (the engine here stops and reports the bad index).This binary search can't find 88 or 3. Change only the comparison in the green box so it prints 8 0 4.
1#include <iostream>2#include <vector>3using namespace std;4 5int bs(const vector<int>& a, int x) {6 int lo = 0, hi = (int)a.size() - 1;7 while (lo hi) {8 int mid = lo + (hi - lo) / 2;9 if (a[mid] == x) return mid;10 if (a[mid] < x) lo = mid + 1;11 else hi = mid - 1;12 }13 return -1;14}15 16int main() {17 vector<int> a = {3, 8, 15, 23, 42, 57, 61, 79, 88};18 cout << bs(a, 88) << " " << bs(a, 3) << " " << bs(a, 42) << endl;19 return 0;20}
8 0 4
lo < hi, the last one is never checked, and 88 and 3 both happen to be the last one left, so it returns -1.Binary search, recursively
✓Write binary search with recursion: if the range a[lo..hi] is empty, return -1; otherwise look at mid and decide whether to go left or right.
4 0 -1
1#include <iostream>2#include <vector>3using namespace std;4 5int bs(const vector<int>& a, int lo, int hi, int x) {6 // lo > hi: -1; mid = lo + (hi - lo) / 2; equal: return mid; otherwise recurse into one side7 return -1;8}9 10int main() {11 vector<int> a = {3, 8, 15, 23, 42, 57, 61, 79, 88};12 cout << bs(a, 0, 8, 42) << " " << bs(a, 0, 8, 3) << " " << bs(a, 0, 8, 50) << endl;13 return 0;14}
The decision tree: comparisons at a glance
Draw the index binary search looks at in each step as a tree: the root is the first mid, to its left the one looked at next if x is smaller, to its right the one if x is bigger. This is the binary search decision tree. The number of comparisons to find an element is its level in this tree.
The decision tree is always very even (full except the last level), so with n elements there are at most ⌊log₂ n⌋ + 1 comparisons.
1#include <iostream>2#include <vector>3using namespace std;4 5// binary search, counting the comparisons: cmp is a reference, so the function changes the caller's variable6int bsearch_count(const vector<int>& a, int x, int& cmp) {7 int lo = 0, hi = (int)a.size() - 1;8 while (lo <= hi) {9 int mid = lo + (hi - lo) / 2;10 cmp++;11 if (a[mid] == x) return mid;12 if (a[mid] < x) lo = mid + 1;13 else hi = mid - 1;14 }15 return -1;16}17 18int main() {19 vector<int> a(10);20 for (int i = 0; i < 10; i++) a[i] = 10 * i;21 int total = 0;22 for (int i = 0; i < 10; i++) { // look for every element once23 int c = 0;24 bsearch_count(a, a[i], c);25 cout << c << ' ';26 total += c;27 }28 cout << "\nbinary ASL = " << total << " / 10 = " << total / 10.0 << endl;29 cout << "sequential ASL = (10 + 1) / 2 = " << 11 / 2.0 << endl;30 return 0;31}
3 2 3 4 1 3 4 2 3 4 binary ASL = 29 / 10 = 2.9 sequential ASL = (10 + 1) / 2 = 5.5
Each number printed is exactly that index's level in the decision tree.
Binary searching 16 elements for the last one: how many comparisons?
1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6 vector<int> a(16);7 for (int i = 0; i < 16; i++) a[i] = i;8 int lo = 0, hi = 15, x = 15, cmp = 0;9 while (lo <= hi) {10 int mid = lo + (hi - lo) / 2;11 cmp++;12 if (a[mid] == x) break;13 if (a[mid] < x) lo = mid + 1;14 else hi = mid - 1;15 }16 cout << cmp << endl;17 return 0;18}
| Search | Needs | ASL (successful) | Time |
|---|---|---|---|
| Sequential | nothing | (n + 1) / 2 | O(n) |
| Binary | sorted, reachable by index (an array) | about log₂(n + 1) − 1 | O(log n) |
Binary search needs to reach the middle one directly by index, so it works only on arrays and vector, not linked lists (std::list). When the data changes often and must still be searched fast, use chapter 4's binary search tree, or the balanced trees two lessons on.
In exams: "draw the binary search decision tree for n elements", "work out the ASL for successful (or unsuccessful) searches", "which elements are compared when looking for some value". For the unsuccessful ASL, add empty "failure nodes" under the decision tree; the comparisons are their parent's level.
Draw the binary search decision tree for a sorted array of 7 elements. With every element equally likely, what is the ASL of a successful search?
The data is in a sorted singly linked list. Why not use binary search?
a[mid] is one step away. In a list, getting to element mid means walking from the head, O(n) just to get there, slower than sequential search. Either use an array, or use a binary search tree.With the STL
Both searches are ready-made in <algorithm>: find(first, last, x) is sequential search and returns an iterator to the first element equal to x, or last if there's none; binary_search(first, last, x) is binary search and only answers true / false.
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> v = {3, 8, 15, 23, 42, 57, 61, 79, 88};8 cout << "42 there? " << (binary_search(v.begin(), v.end(), 42) ? "yes" : "no") << endl;9 cout << "50 there? " << (binary_search(v.begin(), v.end(), 50) ? "yes" : "no") << endl;10 11 auto it = find(v.begin(), v.end(), 57); // sequential search: returns an iterator12 if (it != v.end())13 cout << "57 is at index " << it - v.begin() << endl; // iterator minus begin is the index14 15 vector<int> u = {42, 3, 88, 15, 57}; // not sorted16 cout << "3, unsorted: " << (binary_search(u.begin(), u.end(), 3) ? "yes" : "no") << endl;17 sort(u.begin(), u.end());18 cout << "3, after sorting: " << (binary_search(u.begin(), u.end(), 3) ? "yes" : "no") << endl;19 return 0;20}
42 there? yes 50 there? no 57 is at index 5 3, unsorted: no 3, after sorting: yes
binary_search doesn't check that the data is sorted: hand it an unsorted array and it still looks in the middle and drops half each time; 3 is right there and it says "no". sort first, then search.
How many comparisons does each make? Give find_if and binary_search a lambda that counts:
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> v(1000);8 for (int i = 0; i < 1000; i++) v[i] = 2 * i; // 0 2 4 ... 19989 for (int x : {0, 998, 1998, 999}) {10 long c1 = 0, c2 = 0;11 auto it = find_if(v.begin(), v.end(), [&](int y) { c1++; return y == x; });12 bool has = binary_search(v.begin(), v.end(), x, [&](int a, int b) { c2++; return a < b; });13 cout << "looking for " << x << ": sequential " << c1 << ", binary " << c2 << ", "14 << (it != v.end() && has ? "found" : "not there") << endl;15 }16 return 0;17}
looking for 0: sequential 1, binary 11, found looking for 998: sequential 500, binary 11, found looking for 1998: sequential 1000, binary 11, found looking for 999: sequential 1000, binary 10, not there
Sequential search takes comparisons in proportion to where x is, and a full 1000 when it isn't there; binary search takes ten or so whatever it looks for. Inside, binary_search first uses lower_bound (next lesson) to find the first position not less than x, then makes one more comparison to see whether that is x, so it takes one or two more than our hand-written version; both are O(log n).
| Function | Needs | Returns | Time |
|---|---|---|---|
find(b, e, x) | nothing | an iterator, e if none | O(n) |
find_if(b, e, pred) | nothing | the first one pred holds for | O(n) |
binary_search(b, e, x) | sorted | bool | O(log n) |
sort then binary_search | nothing | bool | O(n log n) to sort once, then O(log n) each |
binary_search only says whether, not where. For the index, or "the first ≥ x", use next lesson's lower_bound. If you search only once or twice, just find: sorting for a single search costs O(n log n), more than O(n).
In interviews: the "binary search" problem (LeetCode 704) wants it written by hand, not a call to binary_search. The usual follow-ups: why the loop condition is <=, why mid + 1, how to write mid so it can't overflow. Answer with the one sentence "if x is there, it's in a[lo..hi]", and every line explains itself.
What does it print? find returns an iterator; take away v.begin() and you get the index. A bool printed with cout comes out as 1 or 0.
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7 vector<int> v = {42, 3, 88, 15, 57};8 auto it = find(v.begin(), v.end(), 15);9 cout << it - v.begin() << " ";10 sort(v.begin(), v.end());11 it = find(v.begin(), v.end(), 15);12 cout << it - v.begin() << " " << binary_search(v.begin(), v.end(), 50) << endl;13 return 0;14}
3 15 42 57 88, so 15 has moved to index 1. 50 isn't there, so binary_search returns false, which cout prints as 0, not -1: it only says yes or no, it never gives an index.A vector holds n numbers that are not sorted, and you only need to check once whether x is there. Which way is fastest?
find walking from start to end; sorting only pays off when many lookups follow. binary_search on an unsorted array can give the wrong answer, and sort then find sorts for nothing.Summary
Sequential search and binary search
- Sentinel: x in a[0], search from the back, one check fewer each round
- Sequential ASL = (n + 1) / 2; binary at most ⌊log₂ n⌋ + 1 comparisons
- Binary search keeps "x is in a[lo..hi]": lo <= hi, mid ± 1; mid = lo + (hi − lo) / 2
- STL: find is O(n); binary_search needs sort first and only says whether
1int lo = 0, hi = (int)a.size() - 1;2while (lo <= hi) {3 int mid = lo + (hi - lo) / 2;4 if (a[mid] == x) return mid;5 if (a[mid] < x) lo = mid + 1; else hi = mid - 1;6}