Complexity, Notations, Sorting & Searching
How fast does the cost grow — and how sorting gets us from n² to n log n.
- place a function on the growth-rate ladder and use O, Ω, Θ
- analyse simple loops, including halving and triangular loops
- trace binary search, selection, insertion, merge and quick sort
- choose a sorting algorithm using time, space and stability
Orders of magnitude — comparing growth, not values
Algorithm A takes 100·n steps, algorithm B takes n². For n = 10, B looks better (100 vs 1000). At n = 100 they tie. Beyond that, B falls hopelessly behind. What matters is how the cost grows once inputs are large, so we ignore constant factors and small inputs.
| Growth | Name | Example |
|---|---|---|
1 | constant | reading L[i] |
log n | logarithmic | binary search, halving loops |
n | linear | scan a list once |
n log n | linearithmic | merge sort, heap sort |
n² | quadratic | selection / insertion sort, two nested loops |
n³ | cubic | naive matrix multiplication |
2ⁿ | exponential | all subsets, naive recursive Fibonacci |
Python does very roughly 10⁷ simple operations per second. So an n² algorithm is fine for n = 10⁴, a lot of trouble for n = 10⁵, and impossible for n = 10⁶. An n log n algorithm handles 10⁶ comfortably.
Roughly how many steps does an n² algorithm take for n = 10⁵?
Order these by growth, slowest-growing first.
Big-O, Ω and Θ
We write f(n) = O(g(n)) if f grows no faster than g: there are constants c and n₀ such that f(n) ≤ c·g(n) for all n ≥ n₀. It is an upper bound.
| Notation | Meaning | Think of it as |
|---|---|---|
O(g) | f ≤ c·g eventually | at most g (upper bound) |
Ω(g) | f ≥ c·g eventually | at least g (lower bound) |
Θ(g) | both O(g) and Ω(g) | exactly g, up to constants |
Working out a bound
Take f(n) = 3n² + 10n + 7. For n ≥ 1, 10n ≤ 10n² and 7 ≤ 7n², so f(n) ≤ 20n². Hence f = O(n²). Also f(n) ≥ 3n² so f = Ω(n²), therefore f = Θ(n²).
- Drop constant factors:
5n = O(n). - Drop lower-order terms:
n² + n log n = O(n²). - Sequential steps add (the larger one wins); nested steps multiply.
O(log₂ n)andO(log₁₀ n)are the same class, since logs differ by a constant factor.
Which is true for f(n) = 5n + 100?
T(n) = n² + n log n + 500. Which is the simplest correct Θ?
Select all true statements.
Analysing loops: best, worst and average cases
The running time can depend on which input of size n we get, not just n. We usually report the worst case: the maximum over all inputs of that size. Average case is often hard to define; best case is rarely useful.
Linear search is O(n) in the worst case — the target is last or missing. It is O(1) in the best case. When we say 'the complexity of linear search' we mean the worst case.
Typical loop patterns
What does this print? (type the exact output)
count = 0
i = 1
while i < 1000:
i = i * 2
count += 1
print(count)What is the worst-case complexity of this code?
for i in range(n):
for j in range(i):
work()Searching: linear vs binary search
If a list is unsorted, the only way to find x is to look at every element: O(n). If the list is sorted, we can do much better by comparing x with the middle element and throwing away half the list each time.
Each comparison halves the window: n → n/2 → n/4 → … → 1. The number of halvings is ⌊log₂ n⌋ + 1. One million items need at most 20 comparisons; one billion need 30.
A sorted list has 1,000,000 elements. At most how many comparisons does binary search need?
What happens if you run binary search on an unsorted list?
Which values does the search for 31 inspect, in order?
L = [2, 5, 9, 14, 20, 31, 40]
lo, hi, trace = 0, len(L) - 1, []
while lo <= hi:
mid = (lo + hi) // 2
trace.append(L[mid])
if L[mid] == 31:
break
elif L[mid] < 31:
lo = mid + 1
else:
hi = mid - 1
print(trace)Sorting: three quadratic algorithms
A sorted list makes searching cheap, and many other problems (duplicates, medians, closest pairs) become easy. We will meet five sorting algorithms this week. First, three simple ones, each O(n²) in the worst case.
Selection sort
Repeatedly select the smallest element of the unsorted part and swap it to the front. After k rounds the first k positions hold the k smallest values in final order. Always Θ(n²) comparisons — it does not care whether the input was already sorted.
Insertion sort
Keep a sorted prefix. Take the next element and insert it by shifting larger elements right, like sorting playing cards in your hand. Worst case (reverse sorted): Θ(n²). Best case (already sorted): Θ(n) — a useful trait.
Bubble sort
Sweep through the list, swapping adjacent out-of-order pairs. After each sweep the largest remaining value has 'bubbled' to its place. Simple, but usually slower than insertion sort in practice.
| Algorithm | Best | Worst | Stable? | In place? |
|---|---|---|---|---|
| Selection | Θ(n²) | Θ(n²) | no (as usually written) | yes |
| Insertion | Θ(n) | Θ(n²) | yes | yes |
| Bubble | Θ(n) with early exit | Θ(n²) | yes | yes |
A sort is stable if equal keys keep their original relative order. Matters when you sort records by one field after sorting by another (e.g. sort students by marks, ties stay alphabetical).
Print the list after each insertion step — what is the output?
L = [5, 2, 4, 1, 3]
for i in range(1, len(L)):
key, j = L[i], i - 1
while j >= 0 and L[j] > key:
L[j + 1] = L[j]
j -= 1
L[j + 1] = key
print(L)Which sort takes only linear time on an already sorted input?
Merge sort — divide, merge, conquer
Quadratic sorts are too slow for a million items. Merge sort gets O(n log n):
Order the steps of merge sort on a list L.
Why n log n?
Merging two sorted lists of total length m takes at most m − 1 comparisons — one pass. Each level of the recursion tree processes n items in total, and there are about log₂ n levels (halving until size 1). So T(n) = 2T(n/2) + n, which solves to Θ(n log n).
It needs O(n) extra space for merging (not in place), and the recursion depth is log n. It is stable if we take from the left half on ties (<= above).
Merging sorted lists of lengths 4 and 5 needs at most how many comparisons?
Why is merge sort's running time Θ(n log n) on every input, including sorted ones?
Quicksort — partition around a pivot
Pick a pivot (say the first element). Rearrange the list so that everything smaller comes before the pivot and everything larger after it. The pivot is then in its final position. Recursively sort the two parts. No merging step is needed.
Running time
If the pivot lands near the middle every time, we get T(n) = 2T(n/2) + n = Θ(n log n). But if the pivot is always the smallest or largest (for example, the first element of a sorted list), the parts have sizes 0 and n−1, giving T(n) = T(n−1) + n = Θ(n²).
| Case | Time |
|---|---|
| Best / average (random pivot) | Θ(n log n) |
| Worst (sorted input, first-element pivot) | Θ(n²) |
| Extra space | O(log n) recursion on average (in place) |
Choosing the pivot at random makes the bad case extraordinarily unlikely on any input. Quicksort is often the fastest in practice because it is in place and cache-friendly.
On an already sorted list with the first element as pivot, quicksort takes…
What does this program print?
L = [5, 1, 8, 3, 9, 2] pivot = L[0] smaller = [x for x in L[1:] if x < pivot] larger = [x for x in L[1:] if x >= pivot] print(smaller, pivot, larger)
Comparing the sorts
| Algorithm | Best | Average | Worst | Extra space | Stable |
|---|---|---|---|---|---|
| Selection | n² | n² | n² | O(1) | no |
| Insertion | n | n² | n² | O(1) | yes |
| Merge | n log n | n log n | n log n | O(n) | yes |
| Quick | n log n | n log n | n² | O(log n) | no |
| Heap (Week 6) | n log n | n log n | n log n | O(1) | no |
Any sorting algorithm that works only by comparing elements needs Ω(n log n) comparisons in the worst case (there are n! orderings and each comparison gives one yes/no answer, so we need at least log₂(n!) = Θ(n log n) comparisons). So merge sort is optimal up to constants.
You must sort 10⁶ records and cannot spare extra memory. Which is the most natural choice?
About how many comparisons (as a power of 10) does an n log n sort of 10⁶ items need? Type the exponent: 10^?
Chapter challenge — Week 2
Which of these is not Θ(n²)?
What does this program print?
def f(n):
c = 0
for i in range(n):
for j in range(i, n):
c += 1
return c
print(f(6))What does this print? (type the exact output)
L = [3, 1, 2]
swaps = 0
for i in range(len(L)):
for j in range(len(L) - 1 - i):
if L[j] > L[j + 1]:
L[j], L[j + 1] = L[j + 1], L[j]
swaps += 1
print(swaps)Arrange the work of binary search for x in a sorted list.
Which statements about merge sort are true?
To search a sorted list of a billion items with binary search needs at most about…
Quicksort's worst case happens when…
If f(n) = 4n³ + n² + 9, what is the exponent k in f(n) = Θ(n^k)?
Practice on LeetCode
Binary search (also 'on the answer'), sorting and selection.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Binary Search ↗ | Easy | the textbook version | |
| Search Insert Position ↗ | Easy | binary search that returns where it would be | |
| Find First and Last Position of Element in Sorted Array ↗ | Medium | two binary searches (left and right bounds) | |
| Search in Rotated Sorted Array ↗ | Medium | binary search when only half is sorted | |
| Koko Eating Bananas ↗ | Medium | binary search on the answer | |
| Merge Sorted Array ↗ | Easy | the merge step of merge sort | |
| Sort Colors ↗ | Medium | partitioning, like quicksort's partition | |
| Sort an Array ↗ | Medium | write merge sort or heap sort yourself | |
| Insertion Sort List ↗ | Medium | insertion sort on a linked list | |
| Kth Largest Element in an Array ↗ | Medium | quickselect (Week 8) or a heap (Week 6) |
Key takeaways
- Compare algorithms by growth rate of the worst-case operation count; use O (upper), Ω (lower) and Θ (tight).
- Binary search needs a sorted list and takes O(log n); linear search works anywhere in O(n).
- Selection, insertion and bubble sort are O(n²). Insertion sort is Θ(n) on sorted input.
- Merge sort is Θ(n log n) always but uses O(n) extra space; quicksort is O(n log n) on average, O(n²) worst case, in place.
- Comparison-based sorting cannot beat Ω(n log n).