Kodewick
Start learning →
Patterns: searching38 / 50

Patterns: searching

Lesson 38 of 50 · Part 7 · Searching · about 22 minutes

This searching review covers binary search whenever you can tell which half holds the answer, walking a matrix sorted by rows and columns from the top right, choosing the right search for the data, and the unsuccessful ASL and block search questions in exams.

Searching questions don't test memorised code; they test two things: can each step throw a big piece away, and which structure suits this data. This lesson takes the three patterns one stage at a time, then works two calculations exams love, and ends with a quick check on chapter 6.

Pattern one: if you can tell which half, you can binary search

The heart of binary search isn't "the array is sorted" but each step can tell which half the answer is in. The classic example is a rotated sorted array: a sorted array cut somewhere in the middle and its two parts swapped, like 4 5 6 7 0 1 2. The whole array isn't sorted, but cut at mid, at least one of the two halves is:

  • a[lo] <= a[mid]: the left half a[lo..mid] is sorted. If x is in [a[lo], a[mid]), go left, otherwise right.
  • Otherwise the right half a[mid..hi] is sorted. If x is in (a[mid], a[hi]], go right, otherwise left.
a (looking for x = 1)45670120123456↑lo↑hi

Finding 1 in the rotated 4 5 6 7 0 1 2: each time, first see which half is sorted, then whether 1 is in that half
main.c
1#include <stdio.h>2 3int search(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[lo] <= a[mid]) {                     // the left half is sorted9            if (a[lo] <= x && x < a[mid]) hi = mid - 1;10            else lo = mid + 1;11        } else {                                   // the right half is sorted12            if (a[mid] < x && x <= a[hi]) lo = mid + 1;13            else hi = mid - 1;14        }15    }16    return -1;17}18 19int main(void) {20    int a[] = {4, 5, 6, 7, 0, 1, 2};21    printf("1 at %d, 6 at %d, 3 at %d\n", search(a, 7, 1), search(a, 7, 6), search(a, 7, 3));22    return 0;23}
Output
1 at 5, 6 at 2, 3 at -1

The same idea solves: the smallest value in a rotated array, finding a "peak" (bigger than both neighbours), and the largest in an array that rises then falls.

Choose one

The rotated array 6 7 1 2 3 4 5, with lo = 0, hi = 6 and mid = 3. Which half is sure to be sorted?

Exercise 1

The smallest in a rotated array

The array was sorted and then rotated, with no repeats. The smallest is the "turning point". Look at a[mid] and a[hi]: a[mid] > a[hi] means the turning point is right of mid, otherwise at mid or left of it.

It should print
0 11 1
exercise1.c
1#include <stdio.h>2 3int find_min(int a[], int n) {4    int lo = 0, hi = n - 1;5    // while lo < hi: mid; a[mid] > a[hi] gives lo = mid + 1, otherwise hi = mid6    return a[lo];7}8 9int main(void) {10    int a[] = {4, 5, 6, 7, 0, 1, 2}, b[] = {11, 13, 15, 17}, c[] = {3, 1, 2};11    printf("%d %d %d\n", find_min(a, 7), find_min(b, 4), find_min(c, 3));12    return 0;13}
Output
Press Run or Ctrl+Enter
Exercise 2

Find a peak

A peak is bigger than both its neighbours (outside both ends counts as minus infinity), and no two neighbours are equal. Look at a[mid] and a[mid + 1]: there is always a peak on the uphill side. Return the index of one peak.

It should print
2 0 3
exercise2.c
1#include <stdio.h>2 3int peak(int a[], int n) {4    int lo = 0, hi = n - 1;5    // while lo < hi: a[mid] < a[mid + 1] means uphill to the right, lo = mid + 1; otherwise hi = mid6    return lo;7}8 9int main(void) {10    int a[] = {1, 3, 5, 4, 2}, b[] = {9, 7, 3}, c[] = {1, 2, 3, 4};11    printf("%d %d %d\n", peak(a, 5), peak(b, 3), peak(c, 4));12    return 0;13}
Output
Press Run or Ctrl+Enter

Pattern two: in two dimensions, find a corner that rules out a whole row

A matrix increases left to right along each row and top to bottom down each column; find x. Start at the top right: it's the largest in its row and the smallest in its column.

  • Bigger than x: everything below in this column is bigger still, the whole column is out, go left.
  • Smaller than x: everything left in this row is smaller still, the whole row is out, go down.

Each step rules out a row or a column, so an m × n matrix takes at most m + n steps. Starting top left doesn't work: right and down both get bigger, so you can't tell which way to go.

Here is the search for 5 in this 4 × 5 matrix, showing what each step rules out: 15, 11 and 7 are all bigger than 5, each rules out a column, go left; 4 is smaller than 5, it rules out its row, go down; and there is 5.

0123401471115125812192369162231013141724
Finding 5 in the matrix: start at 15 in the top-right corner, go left when it's too big and down when it's too small; 5 boxes and it's found
Choose one

In the same matrix, starting from the top-right corner, you look for 13. Which numbers do you look at, in order?

Exercise 3

A matrix sorted by rows and columns

Start at the top right: bigger than x, go left; smaller, go down; equal, found. Print how many steps (boxes looked at) and whether it was found.

It should print
5 found, 5 looked at
20 not found, 5 looked at
exercise3.c
1#include <stdio.h>2 3int m[4][5] = {4    {1, 4, 7, 11, 15},5    {2, 5, 8, 12, 19},6    {3, 6, 9, 16, 22},7    {10, 13, 14, 17, 24},8};9 10void find(int x) {11    int r = 0, c = 4, steps = 0;12    // while r < 4 and c >= 0: steps++; equal, print and return; bigger than x, c--, otherwise r++13    printf("%d not found, %d looked at\n", x, steps);14}15 16int main(void) {17    find(5);18    find(20);19    return 0;20}
Output
Press Run or Ctrl+Enter

Pattern three: which search for which data

The dataUseSearch
unsorted, searched rarelysequential searchO(n)
a sorted array, rarely changedbinary searchO(log n)
often inserted into and deleted from, and still sorteda balanced tree (AVL, red-black)O(log n)
on disk, a lot of ita B+ tree2 to 4 disk reads
looked up only by "equals", no order neededa hash table (Chapter 3)O(1) on average

In exams: multiple choice often asks "which searches need sorted data" (binary search, and block search between blocks), "which work only on sequential storage" (binary search); a decision tree and ASL calculation turns up nearly every year, so keep successful and unsuccessful apart.

Choose one

A phone's contacts: look someone up by exact name, add and delete people often, never list them in order. What fits best?

Choose one

What does binary search need from the data?

Two exam calculations: unsuccessful ASL and block search

Search calculation questions all ask "how many comparisons on average", the average search length, ASL. These two come up most:

  • The ASL of unsuccessful searches: add a "failure node" at every empty place in the decision tree, n + 1 of them for n elements; a failed search makes as many comparisons as its failure node's parent's level; average those.
  • Block search (indexed sequential search): split the n values into b blocks, unsorted inside but in order from block to block, and build an index of "each block's largest". First find the block in the index, then search it sequentially. With s values a block and the index searched sequentially, ASL = (b + 1) / 2 + (s + 1) / 2, smallest when s = √n.
Choose one

Binary search (mid = (lo + hi) / 2) on the sorted list 10 20 30 40 50. What is the ASL of an unsuccessful search?

Choose one

100 numbers in 10 blocks of 10, with sequential search both in the index and inside a block. What is the ASL of a successful search?

Summary

Take-away

Three searching patterns

  • If you can tell which half the answer is in, binary search: rotated arrays, the minimum, a peak
  • A matrix sorted both ways: walk from the top right, a row or column out each step, O(m + n)
  • Unsorted: sequential; a sorted array: binary; often changed: a balanced tree; on disk: a B+ tree; by equality: a hash table
  • Unsuccessful ASL uses the failure nodes' parents; block search is best with s = √n
1while (lo < hi) {2    int mid = lo + (hi - lo) / 2;3    if (the answer is to the right) lo = mid + 1;4    else hi = mid;5}

Chapter 6 quick check

5 questions: a sentinel, binary search's comparisons, a boundary, searching for the answer, and balanced trees. Work out what each prints before you pick.

Guess the outputA wrong guess is fine

Sequential search with a sentinel, from the back, for 8. What does it print?

1#include <stdio.h>2 3int main(void) {4    int a[6] = {0, 8, 3, 8, 5, 1};      // the data in a[1..5]5    int x = 8, i = 5;6    a[0] = x;7    while (a[i] != x) i--;8    printf("%d\n", i);9    return 0;10}
Guess the outputA wrong guess is fine

Binary searching 7 values for 25, which isn't there: how many comparisons before it knows?

1#include <stdio.h>2 3int main(void) {4    int a[7] = {10, 20, 30, 40, 50, 60, 70};5    int lo = 0, hi = 6, x = 25, cmp = 0;6    while (lo <= hi) {7        int mid = lo + (hi - lo) / 2;8        cmp++;9        if (a[mid] == x) break;10        if (a[mid] < x) lo = mid + 1;11        else hi = mid - 1;12    }13    printf("%d\n", cmp);14    return 0;15}
Guess the outputA wrong guess is fine

The condition is a[mid] <= x, looking for 2 in 1 2 2 2 3 5. What does it print?

1#include <stdio.h>2 3int main(void) {4    int a[] = {1, 2, 2, 2, 3, 5};5    int n = 6, x = 2, lo = 0, hi = n;6    while (lo < hi) {7        int mid = lo + (hi - lo) / 2;8        if (a[mid] <= x) lo = mid + 1;9        else hi = mid;10    }11    printf("%d\n", lo);12    return 0;13}
Guess the outputA wrong guess is fine

Searching for the answer: the first positive integer whose cube is at least 50, and how many rounds it took?

1#include <stdio.h>2 3int main(void) {4    int lo = 1, hi = 100, rounds = 0;5    while (lo < hi) {6        int mid = lo + (hi - lo) / 2;7        rounds++;8        if (mid * mid * mid >= 50) hi = mid;9        else lo = mid + 1;10    }11    printf("%d %d\n", lo, rounds);12    return 0;13}
Guess the outputA wrong guess is fine

An AVL tree of height h has at least N(h) = N(h − 1) + N(h − 2) + 1 nodes. At least how many for height 5?

1#include <stdio.h>2 3int main(void) {4    int n[8] = {0, 1, 2};5    for (int h = 3; h <= 6; h++)6        n[h] = n[h - 1] + n[h - 2] + 1;7    printf("%d\n", n[5]);8    return 0;9}