Analysis and searching

How to count the cost of an algorithm by reading its loops, and how binary search finds an item in a sorted array in about log₂ n steps.

About 6 hours of study

Learning objectives

Lessons

  1. 1

    Analysing algorithms

    Count the steps an algorithm takes, read Big-O from loop shapes, and see how fast n², n log n and log n grow.

  2. 2

    Binary search

    Halve a sorted range until the key is found, find the first position of a value, and get the boundaries right.

Module practice

Module quiz

1. What is the Big-O of 5n + 20?
2. Two separate loops run one after the other, each over n items. What is their total cost?
3. What must be true of an array before binary search can be used on it?
4. For n = 5, how many times does the inner statement of for (i = 0; i < n; i++) for (j = i + 1; j < n; j++) run?
5. In a closed-range binary search, lo = 0, hi = 9 and a[mid] is smaller than the key. What are lo and hi next?
6. a = {2, 4, 4, 4, 9}. What does lower_bound(a, 5, 5) return?
7. An O(n²) algorithm takes 1 second for 2,000 items. About how long does it take for 4,000 items?

Sorting ›