Skip to the task
Layout
Back to classic view

You are looking at lesson 6. Your place is still lesson 5, task 1: Functions.

READTask 2 of 28 · step 2: Searching and efficiency

Searching and efficiency

Linear and binary search, how many checks each needs, and selection sort.

You often need to find something in an array: whether it was −5 °C, where the grade 9 is. There are two ways, and they differ in how much work they take.

Check the boxes in turn until you find it. When found, return the index; if you checked them all and didn't find it, return -1 (no index is ever -1).

find(t, n, x):
    for each i from 0 to n - 1:
        if t[i] == x: return i
    return -1

It works on any array. In the worst case (the value isn't there, or it is last) all n boxes are checked.

If the array is sorted, there is a cleverer way, like looking up a word in a dictionary. Look at the middle: if it holds less than you want, the left half is no longer needed; if more, the right half. Every check throws away half of the boxes left.

We look for 23 in 2 5 8 12 16 23 38 56 72 91 (indexes 0–9), with left, right and middle:

Step left right middle t[middle] Decision
1 0 9 4 16 16 < 23 → left = 5
2 5 9 7 56 56 > 23 → right = 6
3 5 6 5 23 found, index 5

Three checks instead of six. If left becomes greater than right, the value isn't there.

On an unsorted array binary search doesn't work: it throws away the half where the value actually was, and returns -1.

How much work

The largest number of checks:

Boxes n Linear Binary
10 10 4
1,000 1,000 10
1,000,000 1,000,000 20

The work of linear search grows with n: twice the data, twice the work. Binary search adds just one step each time n doubles (log₂ n). In the algorithms course you will write this as O(n) and O(log n). Here it is enough to be able to count how many times a loop runs.

Selection sort

To use binary search, the array has to be sorted. The simplest way is selection: find the smallest and swap it with the first, then the smallest of the rest with the second, and so on.

sort(t, n):
    for each i from 0 to n - 2:
        min = the index of the smallest of t[i]..t[n - 1]
        swap t[i] and t[min]

5 4 1 3:

i Smallest of the rest After the swap
0 1 1 4 5 3
1 3 1 3 5 4
2 4 1 3 4 5

Comparisons: 3 + 2 + 1 = 6. For a thousand boxes, 999 + 998 + … + 1 = 499,500. Sorting is expensive, so it is worth it only when you will search many times afterwards. Faster ways to sort are in the Algorithms and Data Structures course.

Swapping two values takes a third variable (temp):

int temp = t[i];
t[i] = t[min];
t[min] = temp;

Without it, t[i] = t[min]; t[min] = t[i]; would give both boxes the same value.