Growth, not the number
Ask what happens when n doubles. The answer names the class: same, doubled, quadrupled, or one more step.
The gap widens
Two cost classes that look close at n of 10 can be millions apart at n of a million.
The question that matters is not the count today but how the count grows when the input doubles. That growth is the cost class.
About 2 min of reading
Before this new lesson, one small question about the lesson you just finished. Recall it, do not look it up.
Compare how four cost shapes grow.
Linear for 10, 20, 40.
Before you run it, say out loud what it will print. Then open the answer.
Quadratic for 5, 10, 20.
Before you run it, say out loud what it will print. Then open the answer.
Halving for 8, 16, 32.
Before you run it, say out loud what it will print. Then open the answer.
Squared of 100000.
Before you run it, say out loud what it will print. Then open the answer.
Before you write anything, put these lines back in the right order. Click a line to move it up one step. This support step is easier than writing code from scratch, and it is here to make the last example stick.
Read the first example one line at a time. A line that prints shows what appears on screen; the rest set things up quietly.
Ask what happens when n doubles. The answer names the class: same, doubled, quadrupled, or one more step.
Two cost classes that look close at n of 10 can be millions apart at n of a million.
def work(n):
s = 0
for i in range(n):
s += 1
return s
print([work(n) for n in (10, 20, 40)])
Double n and the work doubles. That is linear growth.
def work(n):
s = 0
for i in range(n):
for j in range(n):
s += 1
return s
print([work(n) for n in (5, 10, 20)])
Double n and the work quadruples. That is quadratic growth.
def work(n):
s = 0
while n > 1:
n //= 2
s += 1
return s
print([work(n) for n in (8, 16, 32)])
Double n and the work grows by one. Halving each step is logarithmic growth.
def work(n):
return 1 + 1
print([work(n) for n in (1, 1000, 1000000)])
The cost does not look at n at all. That is constant time.
n = 16
print(n, n * n, n // 2)
For n of 16 the three shapes are 16, 256, and 8. The gap widens as n grows.
n = 3
print(n, n * n)
At n of 3 the difference is 3 versus 9. Tiny inputs make bad shapes look fine.
n = 100000
print(n * n)
A hundred thousand squared is ten billion. That many steps takes minutes, not microseconds.
Each one is defined here on this site. Open the entry for the full definition and the other words it points at.