Lesson contents

Counting work and Big O

Count the steps needed for a job as the input grows. Compare a direct read with a search that must check items one by one.

Simple example

Count the checks needed to find 9 by starting at the first position. Print 3. With a known position the same value would take one read.

Start4 7 9
Result3
lesson.jl
function main()
    values = [4, 7, 9]
    checks = 0
    while checks < 3
        checks += 1
        if values[1 + (checks - 1)] == 9
            break
        end
    end
    println(checks)
end

main()
Output
3
Advertisements

Everyday examples

Look up a page number

You know a quotation is on page 20. Do you need to read pages 1 through 19?

Start1…20
Result20

Open directly to the known page. Its number gives you an address.

Inspect unlabelled boxes

A missing badge is in the last of eight boxes. How many lids must you open in a front-to-back search?

Start1…8
Result8

Each box might hold the badge. Doubling the number of boxes can double the worst-case work.

Compare every pair of teammates

Four students each greet every other student once. How many greetings take place?

Start● ● ● ●
Result6

The first has three new partners, the next two and the next one. Pairwise work grows quadratically.

Cost and limits

Big O describes how work grows. A bound on comparisons does not predict the exact running time on a particular computer.