How do we compare algorithms? We use Big O notation β a way to describe how an algorithm's runtime grows as the input size grows.
| Notation | Name | Example | n=1000 |
|---|---|---|---|
| O(1) | Constant | Array access by index | 1 step |
| O(log n) | Logarithmic | Binary search | ~10 steps |
| O(n) | Linear | Linear search | 1000 steps |
| O(n log n) | Linearithmic | Merge sort | ~9966 steps |
| O(nΒ²) | Quadratic | Bubble sort | 1,000,000 steps |
| O(2βΏ) | Exponential | Fibonacci recursive | Impossible! |
Rules of thumb:
# O(n) β single loop
for i in range(n):
print(i)
# O(nΒ²) β nested loop
for i in range(n):
for j in range(n):
print(i, j)
# O(nΒ²) β even with constant factor
for i in range(n):
for j in range(100): # 100 is constant!
print(i, j)
for i in range(n):
for j in range(i):
print(i, j)