PDSA Interactive Book
Week 2

Complexity, Notations, Sorting & Searching

How fast does the cost grow — and how sorting gets us from n² to n log n.

After this chapter you can…
  • 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 rates — drag the input size and compare the curvesInteractive
Time budget — which growth rates finish in a second?Interactive
GrowthNameExample
1constantreading L[i]
log nlogarithmicbinary search, halving loops
nlinearscan a list once
n log nlinearithmicmerge sort, heap sort
n²quadraticselection / insertion sort, two nested loops
n³cubicnaive matrix multiplication
2ⁿexponentialall subsets, naive recursive Fibonacci
A practical rule of thumb

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.

Check yourself

Roughly how many steps does an n² algorithm take for n = 10⁵?

Put in order

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.

NotationMeaningThink of it as
O(g)f ≤ c·g eventuallyat most g (upper bound)
Ω(g)f ≥ c·g eventuallyat 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²).

Rules we use constantly
  • 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) and O(log₁₀ n) are the same class, since logs differ by a constant factor.
Check yourself

Which is true for f(n) = 5n + 100?

Check yourself

T(n) = n² + n log n + 500. Which is the simplest correct Θ?

Check yourself

Select all true statements.

Python · editable
Expected output: 10 4.07 100 3.1007 1000 3.01 100000 3.0001

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.

Python · editable
Expected output: (0, 1) (9, 10) (-1, 10)
Worst case

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

Python · editable
Expected output: 16 4 120
Predict the output

What does this print? (type the exact output)

count = 0
i = 1
while i < 1000:
    i = i * 2
    count += 1
print(count)
Check yourself

What is the worst-case complexity of this code?

for i in range(n):
    for j in range(i):
        work()

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.

Python · editable
Expected output: [10, 13, 14, 29, 37] [10, 13, 14, 29, 37]
Sorting visualiser — pick an algorithm and step through itInteractive
AlgorithmBestWorstStable?In place?
SelectionΘ(n²)Θ(n²)no (as usually written)yes
InsertionΘ(n)Θ(n²)yesyes
BubbleΘ(n) with early exitΘ(n²)yesyes
Stable sort

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).

Predict the output

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)
Check yourself

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):

Put in order

Order the steps of merge sort on a list L.

Python · editable
Expected output: [1, 2, 3, 8, 9, 10, 11] [13, 22, 32, 43, 57, 63, 78, 91]
Merge sort — watch the halves being mergedInteractive

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).

Cost of merge sort

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).

Check yourself

Merging sorted lists of lengths 4 and 5 needs at most how many comparisons?

Check yourself

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.

Python · editable
Expected output: [13, 22, 32, 43, 57, 63, 78, 91]
Quicksort — one partition at a timeInteractive

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²).

CaseTime
Best / average (random pivot)Θ(n log n)
Worst (sorted input, first-element pivot)Θ(n²)
Extra spaceO(log n) recursion on average (in place)
In practice

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.

Check yourself

On an already sorted list with the first element as pivot, quicksort takes…

Predict the output

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

AlgorithmBestAverageWorstExtra spaceStable
Selectionn²n²n²O(1)no
Insertionnn²n²O(1)yes
Mergen log nn log nn log nO(n)yes
Quickn log nn log nn²O(log n)no
Heap (Week 6)n log nn log nn log nO(1)no
Sorting race — exact comparison counts on inputs you chooseInteractive
A lower bound

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.

Check yourself

You must sort 10⁶ records and cannot spare extra memory. Which is the most natural choice?

Check yourself

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

…
Check yourself

Which of these is not Θ(n²)?

Predict the output

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))
Predict the output

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)
Put in order

Arrange the work of binary search for x in a sorted list.

Check yourself

Which statements about merge sort are true?

Check yourself

To search a sorted list of a billion items with binary search needs at most about…

Check yourself

Quicksort's worst case happens when…

Check yourself

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.

How to practise

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.

0 / 10 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Binary Search ↗Easythe textbook version
Search Insert Position ↗Easybinary search that returns where it would be
Find First and Last Position of Element in Sorted Array ↗Mediumtwo binary searches (left and right bounds)
Search in Rotated Sorted Array ↗Mediumbinary search when only half is sorted
Koko Eating Bananas ↗Mediumbinary search on the answer
Merge Sorted Array ↗Easythe merge step of merge sort
Sort Colors ↗Mediumpartitioning, like quicksort's partition
Sort an Array ↗Mediumwrite merge sort or heap sort yourself
Insertion Sort List ↗Mediuminsertion sort on a linked list
Kth Largest Element in an Array ↗Mediumquickselect (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).

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.