Kodewick
Start learning →
Sequential search and binary search35 / 50

Sequential search and binary search

Lesson 35 of 50 · Part 7 · Searching · about 15 minutes

Binary search works only on a sorted array: look at the middle with mid = lo + (hi - lo) / 2, throw away the half that can't hold x, and it needs at most ⌊log₂ n⌋ + 1 comparisons, while sequential search averages (n + 1) / 2.

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.

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:

1a[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.

a (a[0] is the sentinel)2134721907156201234567↑i

Sequential search with a sentinel: looking for 21 in a[1..7]. Put 21 in a[0] first, then walk i back from the end and stop at a 21

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.

Choose one

9 elements, each as likely to be looked for as any other. On average, how many comparisons does a successful sequential search take (ASL)?

Exercise 1

Sequential search with a sentinel

The data is in a[1..n], with a[0] kept for the sentinel. Finish search: put the sentinel in place, search from the back, return the index (0 for not found).

It should print
3 5 0
exercise1.c
1#include <stdio.h>2 3int search(int a[], int n, int x) {4    // a[0] = x; i starts at n, i-- while a[i] != x; return i5    return 0;6}7 8int main(void) {9    int a[8] = {0, 34, 7, 21, 90, 7, 15, 62};   // a[1..7]10    printf("%d %d %d\n", search(a, 7, 21), search(a, 7, 7), search(a, 7, 50));11    return 0;12}
Output
Press Run or Ctrl+Enter

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], so lo = mid + 1.
  • a[mid] > x: likewise, hi = mid − 1.

The same rule, looking for 23 in an array of 9 numbers, watching lo, mid and hi step by step:

a (x = 23)3815234257617988012345678↑lo↑hi
1int lo = 0, hi = n - 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;

Looking for 23 in 3 8 15 23 42 57 61 79 88: if x is there, it is in a[lo..hi]; every look at mid throws half away

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.

Choose one

Binary search for 79 in 3 8 15 23 42 57 61 79 88. Which indexes does it look at as mid, in order?

Fill inTap one to fill a blank; tap a blank to take it back

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 <stdio.h>2 3int find(int a[], int n, int x) {4    int lo = 0, hi = n - 1;5    while (lo <= hi) {6        int mid = lo + ;7        if (a[mid] == x) return mid;8        if (a[mid] < x) lo = mid + 1;9        else hi = mid - 1;10    }11    return -1;12}13 14int main(void) {15    int a[] = {3, 8, 15, 23, 42, 57, 61, 79, 88};16    printf("%d %d %d\n", find(a, 9, 42), find(a, 9, 3), find(a, 9, 50));17    return 0;18}
Change it

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 <stdio.h>2 3int find(int a[], int n, int x) {4    int lo = 0, hi = n - 1;5    while (lo  hi) {6        int mid = lo + (hi - lo) / 2;7        if (a[mid] == x) return mid;8        if (a[mid] < x) lo = mid + 1;9        else hi = mid - 1;10    }11    return -1;12}13 14int main(void) {15    int a[] = {3, 8, 15, 23, 42, 57, 61, 79, 88};16    printf("%d %d %d\n", find(a, 9, 88), find(a, 9, 3), find(a, 9, 42));17    return 0;18}
Should print
8 0 4
Exercise 2

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.

It should print
4 0 -1
exercise2.c
1#include <stdio.h>2 3int find(int a[], int lo, int hi, int x) {4    // lo > hi: -1; mid = lo + (hi - lo) / 2; equal, return mid; otherwise recurse into one side5    return -1;6}7 8int main(void) {9    int a[] = {3, 8, 15, 23, 42, 57, 61, 79, 88};10    printf("%d %d %d\n", find(a, 0, 8, 42), find(a, 0, 8, 3), find(a, 0, 8, 50));11    return 0;12}
Output
Press Run or Ctrl+Enter

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.

4
1
0
2
3
7
5
6
8
9

The decision tree for 10 elements (indexes 0 to 9): index 4 takes 1 comparison, 3, 6 and 9 take 4

The decision tree is always very even (full except the last level), so with n elements there are at most ⌊log₂ n⌋ + 1 comparisons.

main.c
1#include <stdio.h>2 3// binary search, counting the comparisons4int bsearch_count(int a[], int n, int x, int *cmp) {5    int lo = 0, hi = n - 1;6    while (lo <= hi) {7        int mid = lo + (hi - lo) / 2;8        (*cmp)++;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(void) {17    int a[10];18    for (int i = 0; i < 10; i++) a[i] = 10 * i;19    int total = 0;20    for (int i = 0; i < 10; i++) {            // look for every element once21        int c = 0;22        bsearch_count(a, 10, a[i], &c);23        printf("%d ", c);24        total += c;25    }26    printf("\nbinary ASL = %d / 10 = %.1f\n", total, total / 10.0);27    printf("sequential ASL = (10 + 1) / 2 = %.1f\n", 11 / 2.0);28    return 0;29}
Output
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.

Guess the outputA wrong guess is fine

Binary searching 16 elements for the last one: how many comparisons?

1#include <stdio.h>2 3int main(void) {4    int a[16];5    for (int i = 0; i < 16; i++) a[i] = i;6    int lo = 0, hi = 15, x = 15, cmp = 0;7    while (lo <= hi) {8        int mid = lo + (hi - lo) / 2;9        cmp++;10        if (a[mid] == x) break;11        if (a[mid] < x) lo = mid + 1;12        else hi = mid - 1;13    }14    printf("%d\n", cmp);15    return 0;16}
SearchNeedsASL (successful)Time
Sequentialnothing(n + 1) / 2O(n)
Binarysorted, reachable by index (an array)about log₂(n + 1) − 1O(log n)

Binary search needs to reach the middle one directly by index, so it works only on arrays, not linked lists. When the data changes often and must still be searched fast, use last chapter's binary search tree, or the balanced trees coming later in this chapter.

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.

Choose one

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?

Choose one

The data is in a sorted singly linked list. Why not use binary search?

Summary

Take-away

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 can't overflow; decision tree level = comparisons
1int lo = 0, hi = n - 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}