Kodewick
Start learning →
Counting the steps1 / 50

Counting the steps

Lesson 1 of 50 · Part 1 · Getting started: how fast · about 14 minutes

Counting the steps compares algorithms without a stopwatch: count how often the basic operation runs as the data size n grows, so finding the largest takes about n steps and two nested loops about n², and only the fastest-growing part matters.

Two pieces of code both get the right answer. Which is faster? A stopwatch can't settle it: another computer or another compiler, and the result changes. In algorithms, "faster" means something else: how quickly the number of steps grows as the data gets bigger.

Why a stopwatch won't do

The same program can take 2 seconds on an old computer and 0.2 on a new one; with 10 numbers it finishes in a blink, with 10 million it may take a minute. We want a way to talk about speed that doesn't depend on the machine.

A 2016 laptopfind_max(a, 10000000)about 2 s9 999 999 comparisons
A desktop from this yearfind_max(a, 10000000)about 0.2 s9 999 999 comparisons
The same code on the same data (an illustration): the stopwatch differs 10×, the comparisons not by one

So we count steps: one comparison, one assignment, one addition, each is a step. The number of steps depends only on the algorithm and the amount of data, not on the computer.

Choose one

Leo's program takes 3 seconds on his computer; Mia's takes 1 second on hers. Can you say Mia's algorithm is faster?

Which step to count: the basic operation

A program assigns, compares, adds... Counting every kind of step is tedious. Usually you count just one: the statement that runs most often, called the basic operation. It normally sits in the innermost loop; every other statement runs about as often, or far less.

Take a plain summing loop and count every part of it for n = 5:

int sum = 0;①for (int i = 0②; i < n③; i++④)    sum += a[i];⑤printf("%d\n", sum);⑥
  1. ①once
  2. ②once: only at the start
  3. ③n + 1 times: true for i = 0 to 4, false at i = 5, which ends the loop
  4. ④n times
  5. ⑤n times: this is the basic operation
  6. ⑥once
How often each part runs for n = 5: i < n is checked 6 times, the last check fails and the loop ends

Altogether that's 1 + 1 + (n + 1) + n + n + 1 = 3n + 4. What decides the speed is the n runs of sum += a[i]: make n 10 times bigger and the total grows about 10 times too. So in practice you count only the basic operation and say "this code takes about n steps".

Choose one

For n = 10, how many times is the condition i < n in for (int i = 0; i < n; i++) checked?

Counting: finding the largest

To find the largest of n numbers, start with the first and compare each one with "the largest so far".

a4927501234↑i
1int max = a[0];2for (int i = 1; i < n; i++)3    if (a[i] > max)4        max = a[i];

Finding the largest: every number gets a look, so n numbers take n − 1 comparisons

A counter, steps, counts the comparisons. Try a few sizes of n:

main.c
1#include <stdio.h>2 3int find_max(int a[], int n, int *steps) {4    int max = a[0];5    for (int i = 1; i < n; i++) {6        (*steps)++;          // one comparison7        if (a[i] > max)8            max = a[i];9    }10    return max;11}12 13int main(void) {14    int a[1000];15    for (int i = 0; i < 1000; i++)16        a[i] = (i * 37) % 101;17    int sizes[] = {10, 100, 1000};18    for (int k = 0; k < 3; k++) {19        int steps = 0;20        find_max(a, sizes[k], &steps);21        printf("n = %4d  %d comparisons\n", sizes[k], steps);22    }23    return 0;24}
Output
n =   10  9 comparisons
n =  100  99 comparisons
n = 1000  999 comparisons

Make n 10 times bigger and the comparisons grow about 10 times too: the steps grow along with n.

Guess the outputA wrong guess is fine

Finding the largest of 50 numbers; steps counts the comparisons. What does it print?

1#include <stdio.h>2 3int main(void) {4    int a[50], steps = 0;5    for (int i = 0; i < 50; i++)6        a[i] = i % 7;7    int max = a[0];8    for (int i = 1; i < 50; i++) {9        steps++;10        if (a[i] > max)11            max = a[i];12    }13    printf("%d %d\n", max, steps);14    return 0;15}
Change it

Change only the number in the green box so that the program prints 99.

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

Two loops, one inside the other

Another common shape: two loops, one inside the other. Its most common use is comparing every pair once, for example to find out whether an array has any repeats:

a63810123↑i↑j
1for (int i = 0; i < n; i++)2    for (int j = i + 1; j < n; j++)3        if (a[i] == a[j]) return 1;4return 0;

Any repeats? Compare every pair once: 4 numbers take 3 + 2 + 1 = 6 comparisons

For each step of the outer loop, the inner one walks the rest. The simplest form has both loops go round all n times:

Guess the outputA wrong guess is fine

With n = 10, what does this print?

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

You check 10 numbers for repeats by comparing every pair once. If there are no repeats at all, how many comparisons does it take?

Exercise 1

Every pair once

n people each shake hands with every other person once (every pair i < j). Finish the loop to count the handshakes for n = 5.

It should print
10
exercise1.c
1#include <stdio.h>2 3int main(void) {4    int n = 5, steps = 0;5    for (int i = 0; i < n; i++) {6        // j starts at i + 1: count each pair once7    }8    printf("%d\n", steps);9    return 0;10}
Output
Press Run or Ctrl+Enter

Counting other loops

Not every loop runs exactly n times. Before counting, check three things: where it starts, where it stops, and how much it changes each time. Here's n = 64:

add 1 each timefor (i = 0; i < n; i++)64 timesn times
add 2 each timefor (i = 0; i < n; i += 2)32 timesn / 2 times: still grows with n
double each timefor (i = 1; i < n; i *= 2)6 timesgrows very slowly: the log n of lesson 3
How many times three loops run for n = 64
  • Adding 2: only half the runs, n / 2. Make n 10 times bigger and the runs grow 10 times too: it grows like a single pass.
  • Doubling: 1, 2, 4, 8... it passes n in no time. n = 64 takes 6 runs; even n = 1 million takes only 20.
  • A fixed inner loop: for (j = 0; j < 3; j++) runs 3 times however big n is, so inside n outer runs it makes 3n in total. Two nested loops are not always n²: it depends on whether the inner loop grows with n.
Guess the outputA wrong guess is fine

i goes up by 3 each time. What does it print?

1#include <stdio.h>2 3int main(void) {4    int n = 30, steps = 0;5    for (int i = 0; i < n; i += 3)6        steps++;7    printf("%d\n", steps);8    return 0;9}
Guess the outputA wrong guess is fine

The inner loop always runs 4 times. What does it print?

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

Doubling every time

i starts at 1 and doubles each time until it is no longer below n. Finish the loop to count the rounds for n = 64.

It should print
6
exercise2.c
1#include <stdio.h>2 3int main(void) {4    int n = 64, steps = 0;5    int i = 1;6    // in a while (i < n): double i, add 1 to steps7    printf("%d\n", steps);8    return 0;9}
Output
Press Run or Ctrl+Enter

Only the fastest-growing part counts

Write the steps as a formula in n: finding the largest is about n steps, two nested loops about n². Real code has a few extra steps here and there (setting up, the final return), say 3n + 2. For very small n, 3n + 2 is even bigger than n²; but past 3.6, n² overtakes it and the gap keeps widening:

3n + 2 and n² drawn to scale: below n ≈ 3.6 n² is smaller, after that point n² stays bigger and the gap keeps growing

Once n is large, those extras stop mattering:

n3n + 2n²3n + 2 takesn² takes
1032100under 1 µs1 µs
1 0003 0021 000 00030 µs0.01 s
1 000 0003 000 0021 000 000 000 0000.03 sabout 2.8 hours

(“Takes” is at 10⁸ simple steps a second, the rough rule people use for coding problems; the real speed depends on the machine and on what a step does, but not by orders of magnitude.)

With a lot of data, the n² code is hundreds of thousands of times slower than the 3n + 2 one: one is done in 0.03 s, the other takes an afternoon. So when comparing algorithms we look only at the term that grows fastest and ignore the constant in front and the small change at the end. The next lesson writes this down as "Big O".

Choose one

Two pieces of code take these many steps: A takes 100n, B takes n². For n = 1 million, which is faster?

Choose one

The step count is 2n² + 30n + 500. For large n, which term decides the speed?

Summary

Take-away

Speed: count the steps and watch how they grow with n

  • A stopwatch measures the machine; steps measure the algorithm
  • One pass: about n steps; two nested loops: about n² steps
  • For large n, only the fastest-growing term matters
  • Adding 2 is still about n steps, doubling takes only log n; a fixed inner loop is not n²
1for (i = 0; i < n; i++)       // about n steps2    for (j = 0; j < n; j++)   // about n × n steps3        steps++;