Overview
This class completes the recap of Θ (theta) notation — its definition, the "sandwich" graph picture, the quadratic-expression shortcut for finding constants and n₀, and the polynomial rule — and then moves to insertion sort. Insertion sort is motivated by everyday sorting (exam copies, playing cards), traced step by step on arrays, written as pseudocode, and analysed line by line to derive T(n) as a quadratic expression, giving Θ(n²). The class also distinguishes worst, best and average cases, clarifies comparison counts versus swaps, and covers course logistics for Assignment 1 and the lab component.
Learning outcomes
- State the definition of f(n) = Θ(g(n)) using constants C1, C2, N0 and draw the sandwich graph.
- Apply the quadratic shortcut (C1 = a/4, C2 = 7a/4, N0 = 2·max(|b/a|, √(|c/a|))) and the polynomial rule (degree d with positive leading coefficient ⇒ Θ(n^d)).
- Trace insertion sort on an array and count swaps and comparisons.
- Write the insertion sort pseudocode and derive its worst-case comparison count ½n² − ½n.
- Explain why insertion sort is Θ(n²) in the worst case and Θ(n) in the best case (sorted input).
- Perform a line-by-line cost analysis of the pseudocode to obtain T(n) as a quadratic expression.
- Decide when insertion sort is appropriate (small, fairly sorted arrays) versus n log n algorithms for large arrays.
- Express insertion sort's cost as Θ(n + I) in terms of the inversion count I, and explain stability and its dependence on the comparison being strict.
Core concepts
Θ (theta) notation recap
Definition: f(n) = Θ(g(n)) if there exist positive constants C1, C2 and N0 such that C1·g(n) ≤ f(n) ≤ C2·g(n) for all n ≥ N0. Here g(n) is a known function and f describes an algorithm's cost in terms of input size. Why it matters: It is the formal language for stating an algorithm's growth rate; the class uses it to certify insertion sort's complexity. Connection: The graph picture (f(n) sandwiched between C1·g(n) and C2·g(n) from N0 onward, holding till infinity) is also called the sandwich notation. Θ mostly represents the average-case computational complexity. The set interpretation: f(n) = Θ(g(n)) identifies one value from a set of multiple values of g(n), so f(n) is a subset of Θ(g(n)).
Asymptotic analysis and finding n₀
Definition: Analysis done when n tends to infinity (n very, very large). Why it matters: The constants only need to work beyond the boundary N0; N0 is the value beyond which the function's behaviour is confirmed to remain throughout. Connection: For a quadratic expression a known formula gives the constants; in general, for non-quadratic expressions you must think about multiple values and explicitly determine from which value the expression becomes valid.
Polynomial rule
Definition: If a polynomial has highest degree d and the coefficient of the highest-degree term is positive, its order is Θ(n^d), irrespective of the other (negative) terms. Example: n³ − 2n² + 7 has highest-degree term n³, so Θ(n³). (x and n are treated as the same.) Why it matters: It lets you read off complexity from the dominating term instantly. Connection: This is exactly the step used to conclude insertion sort's T(n) is Θ(n²) once T(n) is shown to be quadratic.
Insertion sort — intuition and strategy
Definition: Sorting by picking each element and placing it in its correct position among the already-sorted elements — like a teacher sorting exam copies (pick a copy, compare with existing ones, place it correctly) or arranging a hand of playing cards. Strategy: Keep shifting a pointer from left to right, and keep comparing from right to left — two strategies adopted together. Algorithm description (as stated on the slide): Start with the second element (unsorted array; assume it starts from the sorted position); compare the current element with the one before it; if they are wrongly sorted, swap them; move the current element back through the sorted portion until it is at its correct position; move to the next element and repeat. Conventions: Unless otherwise stated, sorting is ascending. By default the instructor uses indices starting from 1; if a specific location uses index 0 it will be mentioned. Students may use either 0 or 1 in their lab.
Inversions and the Θ(n + I) view
Definition: An inversion is a pair of elements that are out of order. If exactly k elements are out of place, the cost is Θ(n + I), where I is the inversion count: the scan over the array costs n and each swap removes exactly one inversion. Why it matters: I ranges from 0 (already sorted → Θ(n)) to n(n−1)/2 (reverse sorted → Θ(n²)). This is why "always Θ(n)" and "always Θ(n log n)" are both impossible claims for insertion sort. Connection: It sharpens the best/worst-case picture: the n term is the unavoidable scan, the I term is the shifting work.
Stability
Definition: Insertion sort shifts only while A[j] > key, not while A[j] ≥ key. Stopping at an equal element leaves the earlier equal element in front, so the algorithm remains stable. Why it matters: Using ≥ lets the new element jump ahead of equals, which breaks stability — that is the trap. Connection: Merge sort and insertion sort are both stable in their standard versions; this is one reason hybrid sorts use insertion sort on small runs.
When to use insertion sort
Definition: Use it (1) when the array is small and fairly sorted (most elements already in correct position, so the number of swaps is reduced), and (2) because it is the simplest algorithm — easy to implement and understand. Why it matters: For very large arrays, use merge sort, quick sort, etc., whose complexity is of order n log n. Connection: The best-case analysis (sorted input → order n) explains precisely why "fairly sorted" input is cheap.
Worst, best and average case
Definition: Worst case is the maximum time the algorithm will take; anything less than that is better. For insertion sort this is order n². Best case is "totally user dependent" — it depends on how many comparisons we declare per step: if each step needs only one comparison (e.g., input already sorted), the total is order n; if two comparisons per step are allowed, it is still equivalent to order n. Anything less than the worst case can be called average; anything much less than that can be called best. Why it matters: It separates the n² worst-case bound from the n behaviour on sorted data. Connection: Descending input sorted into ascending order gives the maximum (worst) number of comparisons; the worst case is a generic bound — for 7 elements you will never get more than 49 comparisons, in either ascending or descending sorting.
Comparison vs. swapping; time vs. space
Definition: The expression ½n² − ½n is the maximum number of comparisons, not swappings ("swapping is another aspect"). Operations are performed on the same array, so space requirement remains order of n (one element at a time); the analysis discussed is time complexity. Why it matters: Prevents the common exam error of reporting the formula as a swap count. Connection: The in-class swap-counting exercise (answer 17) is a separate count from the comparison formula.
Line-by-line cost analysis (costs c1, c2, …)
Definition: Each pseudocode line is assigned a cost constant (c1, c2, c3, …) and an execution count; the total gives T(n) = f(n), the function representing how the algorithm behaves with respect to input size n. Why it matters: Though the expression looks complicated, it is of the form a n² + b n + c (quadratic), so the complexity is Θ(n²). Connection: The cost constants are just representation values — "you do not need to bother about the c1 c2 c3." Assignment statements (current element = a[i], j = i − 1) are approximately zero cost; the for loop and while loop contain the dominating operation, which is comparison, so they impose the stricter cost. Comments run n − 1 times but cost 0, because a comment does not impose any complexity; multiplying by zero nullifies the count.
Notation caveat (O vs. Θ vs. Ω)
Definition: The instructor uses O in places but says to assume Θ for now; Θ, Ω, O will be discussed in the next lecture. The order is more or less n² for all cases; the notation is a nomenclature perspective (worst → O, average → Θ, best → Ω), but the order of algorithm complexity is n². Why it matters: Exam answers should use the right symbol once the next lecture formalises it. Connection: Bubble sort was mentioned only as "a reciprocal operation of the insertion" (it bubbles the smallest element to the last) and is deferred.
Formulas and maths
- Θ definition: $C_1 g(n) \le f(n) \le C_2 g(n)$ for $n \ge N_0$ Symbols: C1, C2 positive constants bounding f; N0 the boundary beyond which the behaviour holds; g the known comparison function. Used when: proving or stating that an algorithm's cost is tightly bounded by g(n).
- Quadratic shortcut for $f(n) = a n^2 + b n + c$ with $a > 0$: $C_1 = a/4$, $C_2 = 7a/4$, $N_0 = 2 \cdot \max(|b/a|, \sqrt{|c/a|})$ Symbols: a, b, c the coefficients; pick whichever of the two values inside max is larger. Used when: finding the three constants for a quadratic cost function. (If a were negative, that part becomes negative for higher n and starts dominating, changing the entire behaviour.)
- Polynomial rule: polynomial of degree $d$ with positive leading coefficient $\Rightarrow \Theta(n^d)$ Symbols: d the highest degree; leading coefficient must be positive. Used when: reading off complexity from the highest-degree term (e.g., n³ − 2n² + 7 ⇒ Θ(n³)).
- Sum formula: $1 + 2 + 3 + 4 + \dots + n = \frac{n(n+1)}{2}$ Symbols: n the number of terms. Used when: summing the increasing per-step comparison counts.
- Insertion sort comparison count: $1 + 2 + 3 + \dots + (n-1) = \frac{(n-1)n}{2} = \frac{n^2 - n}{2} = \frac{1}{2}n^2 - \frac{1}{2}n$ Symbols: n the number of elements; comparisons in step 1 = 1, step 2 = 2, …, up to n − 1. Used when: bounding the worst-case comparisons; the dominating term is n², hence order n².
- Complexity claim: insertion sort is $O(n^2)$ (worst case) Symbols: n input size. Used when: stating the worst-case bound — a for loop running n times with a while loop inside also running n times gives order n² plus other terms, with n² dominating.
- Best case (sorted input): one comparison per step → total $= n$ comparisons for n elements → order n Symbols: n the number of elements. Used when: analysing already-sorted input.
- Inversion-count bound: insertion sort cost $= \Theta(n + I)$, with $0 \le I \le \frac{n(n-1)}{2}$ Symbols: n the number of elements; I the number of inversions (out-of-order pairs); each swap removes exactly one inversion, the scan costs n. Used when: relating cost to how far the input is from sorted — I = 0 gives Θ(n), I = n(n−1)/2 (reverse sorted) gives Θ(n²).
- While-loop execution count (including the failing check): $2 + 3 + 4 + \dots + n = \frac{n(n+1)}{2} - 1$ Symbols: n the number of elements; obtained by adding one and subtracting one. Used when: counting while-loop executions in the line-by-line analysis.
- Inner statements (not suffering the fail case): $1 + 2 + 3 + \dots + (n-1) = \frac{(n-1)n}{2}$, for each of the two inner statements Symbols: n the number of elements. Used when: counting executions of the two inner statements.
- For-loop: runs $n - 1$ times and fails once → $n$ times total Symbols: n the number of elements (Python omits the last index; starting from index 1). Used when: counting for-loop executions.
- Current-element assignment and $j = i - 1$: $n - 1$ times each; comment: $n - 1$ times at cost 0 Symbols: n the number of elements. Used when: filling the cost table rows.
- Total cost expression: $c_1 n + c_2(n-1) + c_3(n-1) + c_7(n-1) + \left[\frac{n(n+1)}{2} - 1\right] + \left[\frac{n(n-1)}{2}\right] + \left[\frac{n(n-1)}{2}\right]$ Symbols: c1, c2, c3, c7 the per-line cost constants; n the input size. Used when: deriving T(n); collectively this gives an expression like $0.5n^2 + (\text{coefficient})n + \text{constant}$ — a quadratic expression → Θ(n²).
- Worst case for 7 elements: at most $49 = 7^2$ comparisons Symbols: 7 the number of elements. Used when: illustrating that the worst case is a generic bound.
- Merge sort on sorted input: still $O(n \log n)$ — best case equals worst case Symbols: n the input size; it still splits and merges everything. Used when: contrasting with insertion sort's O(n) on sorted input — the reason hybrid sorts (Timsort) use insertion sort on small runs.
Worked examples
Insertion sort trace (first example): Array 18, 5, 7, 9, 14, 2, 11, 16, 3, 1, 20 (11 elements, indices 1 to 11). - Step 1: compare 5 with 18 (key) → swap → 5, 18, 7, 9, 14, 2, 11, 16, 3, 1, 20. First two elements now sorted. - Step 2: element 7 compared with 18 (swap), then with 5 (order same, stop) → 5, 7, 18, 9, 14, 2, 11, 16, 3, 1, 20. Three elements sorted. - Step 3 (index 4): → 5, 7, 9, 18, … - Continuing: 5, 7, 9, 14, 18, …; then 5, 7, 9, 11, 14, 18, …; then 5, 6, 7, 9, 11, 14, 18, 20, and so on. - General logic: start from the second index, compare with the first; on violation, swap; go to the third location and compare with second and first; go to the fourth and compare with third, second, first; and so on.
In-class exercise: Array 17, 13, 4, 8, 3, 2, 7 with indices 1–7. Task: identify the number of swaps required to sort it (swaps = actual change of an element's position, not comparisons). - Step 1 (element 13): 1 swap → 13, 17, 4, 8, 3, 2, 7. Swap count = 1. - Step 2 (element 4): compared with 17 (swap), then 13 (swap) → 4, 13, 17, 8, 3, 2, 7. Swaps = 2. - Step 3 (element 8): compared with 17 (swap), then 13 (swap) → 4, 8, 13, 17, 3, 2, 7. Swaps = 2. - Step 4 (element 3): compared with everyone, 4 swaps → 3, 4, 8, 13, 17, 2, 7. Swaps = 4. - Step 5 (element 2): 5 swaps → 2, 3, 4, 8, 13, 17, 7. Swaps = 5. - Step 6 (element 7): 3 swaps → 2, 3, 4, 7, 8, 13, 17. Swaps = 3. - Total = 1 + 2 + 2 + 4 + 5 + 3 = 17. (A student had answered 17 correctly.)
Algorithm pseudocode (as read out): for j = 2 to n (or 1 to n−1 if index starts at 0); key = a[j] (the second value); i = j − 1; while i > 0 and a[i] > key: swap a[i+1], a[i]; i = i − 1; finally a[i+1] = key.
Sorted input 3, 4, 5, 6, 7, 8: choosing each next element gives one comparison, while loop fails, no swap → 5 comparisons for 5 elements → best case = n.
Comparison count per step (worst case): step 1: compare 2nd with 1st → 1 comparison; step 2: compare 3rd with 2nd, then 2nd with 1st → 2 comparisons; step 3: 3 comparisons; step 4: 4 comparisons; … up to n − 1 (since a comparison needs two elements).
7 elements: a student computed 21 from ½n² − ½n; the instructor clarified this is the maximum number of comparisons and actual counts depend on the elements (could be less).
Descending vs. ascending for an unsorted array: a student noted 7 steps for ascending and 11 steps for descending; the instructor replied that in the worst case neither exceeds 49 comparisons for 7 elements.
Trace on A = [5, 2, 4, 6, 1, 3] (standard insertion sort, outer loop iterations): - Iteration 1 → [2, 5, 4, 6, 1, 3] - Iteration 2 → [2, 4, 5, 6, 1, 3] - Iteration 3 (key = 6) → unchanged, [2, 4, 5, 6, 1, 3]
Questions asked in class
Q (Parambir): In the previous class's example 3n² − 9n + 17, we did not take n = 1, 2, or 3 because even though the answer was positive, the n component was missing or 0. Is this statement correct? A: Yes, that is correct. At n = 1 it is positive, at n = 2 it is positive, so n₀ can be 1. If the function is positive for n = 1, 2, 3 and so on, we can declare n₀ = 1, because it is a positive function. There is no need to take 17 or the n component otherwise. Good question for everyone.
Q (Parambir): Why is the complexity n² and not O(n), since the number of iterations equals the number of elements — we sort each element one by one? A: The number of steps is n − 1. But in each step the number of comparisons increases: step 1 does 1 comparison, step 2 does 2, step 3 does 3, step 4 does 4, up to n − 1 comparisons (comparisons happen even when no swap is needed). Using 1 + 2 + … + n = n(n+1)/2, the total is (n − 1)·n/2 = (n² − n)/2 = ½n² − ½n; the dominating term is n², so it is order n². It is not linear because we do more than one comparison per step — at every step we must reverse back to the first position from the chosen point, so comparisons keep increasing. The worst-case time complexity is n².
Q (Sunil Kumar): Since the left side is already
Key takeaways
- Insertion sort costs Θ(n + I): the scan is n, and each swap removes exactly one inversion. I = 0 (sorted) gives Θ(n); I = n(n−1)/2 (reverse sorted) gives Θ(n²) — so "always Θ(n)" and "always Θ(n log n)" are both impossible.
- The while condition uses strict A[j] > key, not ≥; stopping at an equal element keeps the earlier one in front, so insertion sort is stable. Using ≥ breaks stability.
- Merge sort and insertion sort are both stable in their standard versions.
- Merge sort stays O(n log n) even on sorted input — best case equals worst case — which is the big contrast with insertion sort's O(n) on sorted input and the reason hybrid sorts (Timsort) use insertion sort on small runs.
Glossary
- Inversion: a pair of elements that are out of order; insertion sort removes exactly one per swap, so cost is Θ(n + I).
- Stable sort: equal elements keep their original relative order; insertion sort is stable because it shifts only while A[j] > key.
- Timsort: a hybrid sort that uses insertion sort on small runs, exploiting its O(n) behaviour on nearly sorted data.