Week 5: Basic Sorting

Computer Algorithms (506994-002)

Ridho Hendra, Ph.D · Dept. of Intelligent Computing · Mon [1-3] · Building A, Room 703
Department of Intelligent Computing

Where We Are

Wk 1
Introduction
Wk 2
Algorithm Concepts
Wk 3
Complexity Analysis
Wk 4
Recursion & Recurrence
Wk 5
Basic Sorting
Wk 6
Advanced Sorting
Wk 7
Searching
Wk 8
Midterm Exam
Wk 9
Divide & Conquer
Wk 10
Greedy Algorithms
Wk 11
Dynamic Programming I
Wk 12
Dynamic Programming II
Wk 13
Graph Representation
Wk 14
Shortest Path
Wk 15
Final Exam
Department of Intelligent Computing

Last Week, This Week

  • Last week delivered: a way to trace and bound the cost of
    algorithms that call themselves - recursion trees, recurrence
    relations, and how to solve them.
  • Last week left broken: all of that machinery measures cost, but
    gives us zero new tools for actually organizing data. CampusNav's
    room directory is still exactly what it was in Week 1 - an unsorted
    array - and every operation on it still means brute-force scanning.
Department of Intelligent Computing

Key Words Today

  • Sorted: every element in order - for CampusNav, buildings listed
    alphabetically instead of in whatever order they were scraped.
  • In-place: an algorithm that rearranges the array itself, using
    only a constant amount of extra memory ( space).
  • Stable: equal-key elements keep their original relative order
    after sorting - matters more than it sounds like it should.
  • Loop invariant: a statement true before, during, and after every
    pass of a loop - today's tool for proving a sort is correct.
Department of Intelligent Computing

The Directory Is Chaos

CampusNav's room directory has grown from one building's 40 rooms to
the whole campus's 1,200 - but every entry was added in whatever
order a staff member typed it in, not alphabetically. The team wants
the app to show buildings in a clean A-to-Z list, the way any map or
directory should look. Right now, the only way to get that is for
someone to print the whole list, spread it on a table, and physically
re-order it by hand - and every time one new building signs up, that
person has to do it all over again from scratch.

Department of Intelligent Computing

How Long Does That Actually Take?

Staff hand-reordering, 1,200 entries
hours, and error-prone
Any of today's three sorts, run once
well under a second
Illustrative, not measured data: the point is the gap, not the exact numbers.

Even the simplest sorting method a computer runs beats a human doing
it by hand - but "simplest" still has a hidden cost, coming up next.

Department of Intelligent Computing

What Else This Actually Costs

  • A method that "looks sorted" after a few manual passes might still
    have entries out of place - nobody can prove a hand-shuffled list
    is actually, fully sorted.
  • A method that's fine on 40 rooms can become painfully slow once the
    whole campus (or a whole company's dataset) is involved - some
    "obviously correct" sorting methods scale far worse than others.
  • Two sorting methods can look interchangeable on a small example and
    behave very differently once real data (duplicates, near-sorted
    updates, huge size) shows up.
In industry: "implement a sort" and "explain why insertion sort beats quicksort on nearly-sorted data" are both extremely common interview questions - not because sorting is exotic, but because reasoning precisely about a simple algorithm's correctness and cost is the actual skill being tested.
Department of Intelligent Computing

It Gets Worse As the Directory Grows

One building, ~40 rooms
~1,600 comparisons
Whole campus, ~1,200 rooms
~1,440,000 comparisons
Campus + partner campuses, ~10,000 rooms
~100,000,000 comparisons
Illustrative, not measured data: today's three sorts all grow roughly like n², the point is the trend.

Today's methods will get CampusNav's directory sorted - and, as we'll
see in Week 6, they are not the method that scales to a
university-sized directory.

Department of Intelligent Computing

This Week's Question

"How do we turn CampusNav's messy directory into a provably sorted list - and how do we know our method is actually correct, not just usually right?"
Department of Intelligent Computing

By the End of This Week, You Can

  1. Trace bubble sort, selection sort, and insertion sort by hand on a
    small array, one pass at a time.
  2. State and compare each sort's worst-, average-, and best-case time
    complexity, and explain why insertion sort's best case differs from
    the other two.
  3. Prove insertion sort correct using a loop invariant - stated,
    and shown to hold at initialization, maintenance, and termination.
  4. Determine whether a sort is stable, explain why it matters, and
    name which of today's three sorts are (and aren't).
Department of Intelligent Computing

This Problem Is Not New

Sorting is old. Here's how old, and why that matters.
  • Sorting is one of the oldest problems in computing - punched-card
    tabulating machines were doing mechanical sorting passes in the
    1920s-30s, decades before stored-program computers existed.
  • Donald Knuth's The Art of Computer Programming, Vol. 3 (1973)
    devotes an entire volume to sorting and searching - precisely
    because "just sort it" hides a surprisingly deep set of
    correctness and efficiency questions.
  • Insertion sort is not a computer's invention at all - it's
    literally how most people sort a hand of playing cards. Hold that
    image; it returns as today's third algorithm.
Department of Intelligent Computing

Why Learn the "Slow" Sorts First?

Decades old, provably correct - and still where every course starts.
Bubble, selection, and insertion sort are all decades old, all provably correct, and all still taught first - not because they're the fastest choice, but because they're the simplest place to practice proving an algorithm correct before tackling faster ones (Week 6).
Department of Intelligent Computing

Sorting, Stated Precisely

Fifty years of study point at one precise problem. Here it is. (CLRS - Cormen/Leiserson/Rivest/Stein's Introduction to Algorithms, 4th ed, §2.1)

Given an array , rearrange its elements into a new order
such that , using
only the elements originally present (no adding, dropping, or
inventing values).

  • In-place: rearranges itself, using extra space beyond
    the array.
  • Stable: if two elements have equal keys, the one that appeared
    first in still appears first in .

Every sort this week satisfies the first definition. Whether each one
satisfies stability is exactly today's twist.

Department of Intelligent Computing

Key Words Today

  • Pass: one full sweep of the algorithm's main loop over the
    (remaining) array.
  • Adaptive: an algorithm that runs faster when the input is
    already partly sorted, instead of doing the same fixed amount of
    work regardless.
  • Comparison / swap / shift: the three basic operations a sort
    performs - today's three algorithms use different mixes of them.
  • Correctness proof: an argument that covers every valid input,
    not a demonstration on one example - today, a loop invariant.
Department of Intelligent Computing

Bubble Sort: Idea and Pseudocode

First of three. Repeatedly swap neighbors out of order. (CLRS 4th ed, Problem 2-2)

Walk left to right through the array. Compare each pair of neighbors;
if they're out of order, swap them. The largest unsorted element
"bubbles" all the way to the end of the array by the end of one pass.
Repeat, one fewer element each time, until a pass makes no swaps at
all.

BUBBLE-SORT(A):
    n = length(A)
    for i = 0 to n - 2:
        swapped = false
        for j = 0 to n - 2 - i:
            if A[j] > A[j+1]:
                swap A[j] and A[j+1]
                swapped = true
        if not swapped:
            break
Department of Intelligent Computing
Bubble sort · worked example 1 of 3 (simple)

Three Elements: [3, 1, 2]

The smallest case that still shows both a swap and an early exit.
GoalSort [3, 1, 2] and watch the early-exit flag actually fire.
1
Pass 1 (2 cmp)
Compare (3,1): swap → [1,3,2]. Compare (3,2): swap → [1,2,3]. Two swaps, array already sorted.
→
2
Pass 2 (1 cmp)
Compare (1,2): already in order, no swap. swapped stays false.
→
3
Result
Loop breaks early. Sorted in 2 passes, 3 comparisons total, done before reaching the worst-case n−1 = 2 passes' full cost.
✓
Conclusion[3, 1, 2] → [1, 2, 3] in 2 passes, 3 comparisons.
💡
Key takeawayEvery pass either fixes something or proves nothing's left to fix - that second case is the early exit.
Department of Intelligent Computing
Bubble sort · worked example 2 of 3 (moderate)

Full Trace with Cost: [5, 2, 4, 1, 3]

A moderate, unsorted array. No pass exits early until the last one.
GoalSort in full, and count every comparison pass by pass.
1
Pass 1 (4 cmp)
before
5
2
4
1
3
after
2
4
1
3
5
3 swaps, 5 bubbles to the end.
→
2
Pass 2 (3 cmp)
after
2
1
3
4
5
2 swaps, 4 settles next.
→
3
Pass 3 (2 cmp)
after
1
2
3
4
5
1 swap, 3 settles next.
→
4
Pass 4 (1 cmp)
after
1
2
3
4
5
0 swaps - sorted, but the flag check happens next pass.
✓
ConclusionSorted after 4 passes, 4+3+2+1 = 10 comparisons total - matches the worst case exactly.
💡
Key takeawayEach pass settles one more maximum into place; the comparison count shrinks by one every pass.
Department of Intelligent Computing
Bubble sort · worked example 3 of 3 (harder)

Nearly-Sorted Input: [1, 2, 3, 5, 4]

Only the last two entries are out of order. Does the early-exit flag notice?
GoalShow the early-exit flag turns a nearly-sorted input into far less than the worst-case work.
1
Setup
[1, 2, 3, 5, 4] - a reverse-sorted input would need n−1 = 4 passes. This one shouldn't.
→
2
Pass 1
(1,2) (2,3) (3,5): no swaps. (5,4): swap → [1,2,3,4,5]. swapped = true.
→
3
Pass 2
Every neighbor pair already in order. Zero swaps. swapped stays false → loop exits.
★
What this proves
2 passes total, not the 4 a reverse-sorted input would cost. Nearly-sorted input runs close to O(n), not O(n²).
✓
ConclusionBubble sort is adaptive: its actual cost shrinks toward O(n) as the input gets closer to sorted.
💡
Key takeawayThe early-exit flag is what turns "provably O(n²)" into "close to O(n) in practice" for realistic, mostly-sorted inputs.
Department of Intelligent Computing
Bubble sort · proving the bound

Proving the O(n²) Bound

Every earlier trace counted comparisons on one input. Here's the general argument, in four steps.
GoalShow worst-case comparisons = n(n−1)/2, hence O(n²).
1
Count one input
n = 5, no early exit: pass 1 makes 4 comparisons, pass 2 makes 3, pass 3 makes 2, pass 4 makes 1. Total = 4+3+2+1 = 10.
→
2
Generalize
For any n, pass k compares (n−k) pairs. Total comparisons = (n−1) + (n−2) + … + 1.
→
3
Closed form
That sum is n(n−1)/2 (Week 3's arithmetic-series rule). Check: n=5 → 5×4/2 = 10. Matches step 1.
★
Shortcut
Drop the −n term and the constant ½ (Week 3's rules) → O(n²) directly from the leading n²/2 term.
✓
ConclusionWorst-case comparisons = n(n−1)/2 → O(n²) - this derivation backs every O(n²) claim in Weeks 5-6.
💡
Key takeawayTo prove a bound: count on one concrete input, then generalize the pattern into a closed form.
Department of Intelligent Computing

Bubble Sort: Cost and Stability

Average case: the expected cost over a "typical," randomly-ordered input - not the worst case (an adversarial input) or the best case (already sorted).
Worst case - reverse-sorted input, every pair swaps every pass
Average case
Best case - already sorted, one pass, zero swaps, exit early
Space - in-place
Stable? Yes - swaps only strictly-greater neighbors, so equal keys never cross
Adaptive? Yes, with the swapped flag; without it, always

O(n²) comparisons/swaps in the worst
case, but the early-exit flag is what makes bubble sort notice a
sorted (or nearly-sorted) array instead of blindly grinding through it.

Department of Intelligent Computing

Selection Sort: Idea and Pseudocode

Second of three. Repeatedly grab the smallest remaining. (CLRS 4th ed, Exercise 2.2-2)

Scan the unsorted remainder for its minimum, swap it into the next
open position at the front, repeat on the shrinking remainder.

SELECTION-SORT(A):
    n = length(A)
    for i = 0 to n - 2:
        min_idx = i
        for j = i + 1 to n - 1:
            if A[j] < A[min_idx]:
                min_idx = j
        swap A[i] and A[min_idx]

Notice: the inner loop always scans the entire remainder, no matter
how sorted it already is - there is no early exit here.

Department of Intelligent Computing
Selection sort · worked example 1 of 3 (simple)

Three Elements: [3, 1, 2]

The smallest case that still needs two full scans.
GoalSort [3, 1, 2] and notice the scan never shortens.
1
Pass 1
Scan indices 1-2 for the minimum of the whole array: 1, at index 1. Swap index 0 and 1 → [1, 3, 2].
→
2
Pass 2
Scan index 2 for the minimum of the remainder: 2, at index 2. Swap index 1 and 2 → [1, 2, 3].
→
3
Result
Sorted in 2 passes, 1+2 = 3 comparisons - the scan runs full-length every single pass, no shortcuts.
✓
Conclusion[3, 1, 2] → [1, 2, 3] in 2 passes, 3 comparisons, zero early exits.
💡
Key takeawaySelection sort's scan is always full-length - there is no flag to check and no way to stop early.
Department of Intelligent Computing
Selection sort · worked example 2 of 3 (moderate)

Full Trace: [5, 2, 4, 1, 3]

Same array as bubble sort's moderate example - same result, different mechanics.
GoalSort in full, one minimum swapped into place per pass.
1
Pass 1
after
1
2
4
5
3
Min of whole array (1) swaps into index 0.
→
2
Pass 2
after
1
2
4
5
3
Min of remainder (2) is already at index 1 - "swaps with itself."
→
3
Pass 3
after
1
2
3
5
4
Min of remainder (3) swaps into index 2.
→
4
Pass 4
after
1
2
3
4
5
Min of remainder (4) swaps into index 3.
✓
ConclusionSorted after 4 passes - every pass scanned the full remainder, whether it needed to or not.
💡
Key takeawayPass 2's minimum was already in place - it still scanned everything and "swapped with itself."
Department of Intelligent Computing
Selection sort · worked example 3 of 3 (harder)

Stability Breaks: [4a, 4b, 1c]

Tag two equal-key elements so we can track them (subscripts are labels, not values).
GoalFind one input where selection sort scrambles equal-key order.
1
Scan
A = [4a, 4b, 1c]. Minimum of the whole array is 1c, at index 2.
→
2
Swap
Swap index 0 and index 2 → A = [1c, 4b, 4a].
→
3
Compare orders
4a was before 4b originally. After one swap, 4b comes before 4a - their relative order flipped.
★
Not a fluke
A different array, e.g. [3a, 1b, 3c], happens to stay stable after its own swap - but "sometimes stable" is not the same claim as "stable."
✓
ConclusionOne 3-element counterexample proves naive selection sort is NOT stable.
💡
Key takeawayOne counterexample disqualifies a general claim - even if other inputs happen to behave.
Department of Intelligent Computing
Selection sort · proving the bound

Cost on Every Input, Not Just the Worst

Bubble sort's bound was a worst case. Selection sort's is not - it's every case.
GoalShow selection sort makes exactly n(n−1)/2 comparisons, on every input.
1
Inner loop for i
For a fixed outer index i, the inner loop always runs (n−1−i) comparisons - the array's contents never change that count.
→
2
Sum over i
i = 0 gives n−1, i = 1 gives n−2, …, i = n−2 gives 1. Same sum as bubble sort → n(n−1)/2.
→
3
Try it sorted
Run it on the already-sorted [1,2,3,4,5]: still 4+3+2+1 = 10 comparisons, even though every "swap" is a no-op.
★
Contrast with bubble
Identical formula to bubble sort's worst case - but bubble and insertion sort only pay it in the worst case. Selection sort always pays it.
✓
ConclusionSelection sort's best case is still Θ(n²) - the sorted-input shortcut other sorts get simply doesn't exist here.
💡
Key takeawayA comparison count that doesn't depend on the data isn't a worst case - it's the only case.
Department of Intelligent Computing

Selection Sort: Cost and Stability

Worst case
Average case
Best case - even on an already-sorted array, still scans everything
Space - in-place
Stable? No (naive form) - see the [4a, 4b, 1c] counterexample
Adaptive? No - the inner scan never shortens or exits early

The one thing selection sort does guarantee: exactly swaps,
total, regardless of input. If writes are expensive (e.g. writing to
flash memory) and comparisons are cheap, that can matter - but it
never adapts to a nearly-sorted array the way bubble or insertion sort do.

Department of Intelligent Computing

Insertion Sort: Idea and Pseudocode

Third of three. This is how most people actually sort a hand of cards. (CLRS 4th ed, §2.1)

Grow a sorted prefix one element at a time: take the next element
(key) and slide it left past every sorted element greater than it,
until it lands in its correct spot.

INSERTION-SORT(A):
    n = length(A)
    for i = 1 to n - 1:
        key = A[i]
        j = i - 1
        while j >= 0 and A[j] > key:
            A[j+1] = A[j]
            j = j - 1
        A[j+1] = key
Department of Intelligent Computing
Insertion sort · worked example 1 of 3 (simple)

Three Elements: [2, 3, 1]

The smallest case that shows both "no shift needed" and "shift past everything."
GoalSort [2, 3, 1] and see cost track distance-to-travel.
1
i=1, key=3
A[0]=2 is not > 3, so the while loop never runs. key drops back in place: [2, 3, 1]. Zero shifts.
→
2
i=2, key=1
A[1]=3 > 1: shift. A[0]=2 > 1: shift. j = -1: stop. Place key at index 0 → [1, 2, 3]. Two shifts.
→
3
Result
Sorted in 2 passes, 2 shifts total - all the cost came from the one key that had to travel the whole way.
✓
Conclusion[2, 3, 1] → [1, 2, 3] in 2 passes, 2 shifts.
💡
Key takeawayCost equals how far each key must travel to reach its correct spot - not how many elements exist.
Department of Intelligent Computing
Insertion sort · worked example 2 of 3 (moderate)

Full Trace, Zoomed Into One Pass: [5, 2, 4, 1, 3]

Pass by pass, then one pass under the microscope, shift by shift.
GoalSort in full, and see exactly what one pass costs, comparison by comparison.
1
i=1, key=2
A[0]=5 > 2: shift. j=-1: stop. Place at 0 → [2,5,4,1,3]. One shift.
→
2
i=2, key=4
A[1]=5 > 4: shift. A[0]=2 not > 4: stop. Place at 1 → [2,4,5,1,3]. One shift.
→
3
i=3, key=1
A[2]=5, A[1]=4, A[0]=2 all > 1: three shifts. Place at 0 → [1,2,4,5,3].
★
Zoom: inside i=3
j=2: 5>1 shift, j=1: 4>1 shift, j=0: 2>1 shift, j=-1 stop, place 1 at index 0. Three comparisons, three shifts, one placement.
✓
ConclusionOne more pass, i=4 (key=3, two shifts), finishes the sort: [1,2,3,4,5].
💡
Key takeawayEvery iteration ends with A[0..i] sorted - that sentence is about to become a formal proof.
Department of Intelligent Computing
Insertion sort · worked example 3 of 3 (harder)

Best Case vs. Worst Case

Same algorithm, two inputs at opposite extremes.
GoalShow why insertion sort's best case is O(n) when selection sort's isn't.
1
Worst: [5,4,3,2,1]
Every key must jump past every earlier element. Shifts: 1+2+3+4 = 10, matching n(n−1)/2.
→
2
Count
Same closed form as bubble and selection sort's worst case → O(n²).
3
Best: [1,2,3,4,5]
The while condition fails immediately, every time. Zero shifts, n−1 = 4 comparisons total → O(n).
★
Why selection can't do this
Selection sort's inner scan never shortens, so it can't reach O(n) even on a fully-sorted array.
✓
ConclusionInsertion sort adapts to how sorted the input already is; selection sort never does.
💡
Key takeawayA best case isn't automatic - it depends on whether the algorithm's structure can detect and exploit an easy input.
Department of Intelligent Computing

Proving Insertion Sort Correct: The Invariant

"It matched my trace" is not a proof. Here's the real one.

Loop invariant: at the start of each iteration of the outer
for loop (indexed by i), the subarray A[0..i-1] consists of
exactly the elements that originally occupied A[0..i-1], but in
sorted order.

A correctness proof using a loop invariant has three parts, mirroring
mathematical induction from Week 4.

Department of Intelligent Computing

The Three Parts of the Proof

Same shape as the induction proofs from Week 4.
  • Initialization - it holds before the first iteration.
  • Maintenance - if it holds before an iteration, it still holds
    before the next one.
  • Termination - when the loop ends, the invariant gives the claim
    we wanted to prove.
Department of Intelligent Computing
Insertion sort · proving correctness

The Proof, All Three Parts

Every trace above matched the invariant. Here's why it holds on every input, not just the ones we traced.
GoalProve: after the loop, A[0..n−1] holds the original elements, sorted - for every input.
1
Initialization
Before the first iteration, i=1: the claim is about A[0..0], a single element. Trivially sorted - no pair to be out of order.
→
2
Maintenance
Assuming A[0..i-1] is sorted: shifting moves only elements strictly greater than key; key drops into the gap. A[0..i] is sorted - invariant now one wider.
→
3
Termination
The loop stops when i=n. The invariant at i=n says A[0..n−1] is sorted - that subarray is the entire array.
★
Why all three parts
Initialization + maintenance alone only show the invariant holds at the start of every iteration. Termination is what connects that to a claim about the finished array.
✓
ConclusionCorrect on every valid input - not just the traces we drew.
💡
Key takeawayA strict comparison (>, not >=) is what keeps the maintenance step - and stability - intact.
Department of Intelligent Computing

Insertion Sort: Cost and Stability

Worst case - reverse-sorted input, every key shifts all the way left
Average case
Best case - already sorted, the while condition fails immediately every time
Space - in-place
Stable? Yes - the while only shifts elements strictly greater than key, so equal keys are never jumped
Adaptive? Yes - cost scales with how far out of place each element already is

This is why insertion sort mirrors sorting a hand of cards: cards
you draw that are already close to correctly placed cost almost
nothing to insert.

Department of Intelligent Computing

All Three, Side by Side

Bubble Selection Insertion
Worst
Average
Best
Space
Stable? Yes No Yes
Adaptive? Yes (w/ flag) No Yes

Same worst-case row, three very different real-world personalities -
and that gap is exactly next week's setup: even the best of these
three is still worst case.

Department of Intelligent Computing
CampusNav · worked example 1 of 3

Sorting the Room Directory, by Insertion

Everything above, applied to the actual pain from the start of this deck.
GoalA 5-entry sample, scraped in signage order, sorted alphabetically.
1
i=1: Arts
after
Arts
Music
Science
Gym
Library
Shifts past Music.
→
2
i=2: Science
after
Arts
Music
Science
Gym
Library
Already greater than Music - zero shifts.
→
3
i=3: Gym
after
Arts
Gym
Music
Science
Library
Shifts past Science and Music.
→
4
i=4: Library
after
Arts
Gym
Library
Music
Science
Shifts past Science and Music.
✓
ConclusionFour passes, done - and, unlike a staff member reordering by hand, we can now prove the result is sorted, on any input.
💡
Key takeawayFive entries, four passes - the same proof that covered every array covers this one too.
Department of Intelligent Computing
CampusNav · worked example 2 of 3

The Same Directory, by Selection

Same 5 entries, same final order - a very different amount of work along the way.
GoalSort the same directory with selection sort, and watch the scans.
1
Pass 1
after
Arts
Music
Science
Gym
Library
Min of all 5 (Arts) swaps to index 0.
→
2
Pass 2
after
Arts
Gym
Science
Music
Library
Min of remainder (Gym) swaps to index 1.
→
3
Pass 3
after
Arts
Gym
Library
Music
Science
Min of remainder (Library) swaps to index 2.
→
4
Pass 4
after
Arts
Gym
Library
Music
Science
Music was already correct - still scanned to confirm it.
✓
ConclusionSame final order as the insertion-sort trace above.
💡
Key takeawayThis is the "no early exit" row from the cost table, made concrete: selection sort pays full price even when nothing needs to move.
Department of Intelligent Computing
CampusNav · worked example 3 of 3 (harder)

Re-Sorting by Floor: Stable vs. Unstable

The directory is already alphabetical. Now the team wants it grouped by floor instead.
GoalRe-sort [Arts(F2), Music(F2), Gym(F1)] by floor, two ways.
1
Setup
Already A-to-Z: Arts (Floor 2), Music (Floor 2), Gym (Floor 1). Re-sort by floor, ascending.
2
Stable (insertion)
Groups Floor 1 first, Floor 2 after, in original order → [Gym, Arts, Music]. Arts still before Music.
3
Unstable (naive selection)
Min-scan finds Gym (Floor 1) at index 2, swaps it to the front → [Gym, Music, Arts]. Arts and Music flipped!
★
Why
The swap that brought Gym to the front happened to relocate Arts past Music - the exact [4a,4b,1c] mechanism, now with real room names.
✓
ConclusionSame input, same sort key, two different orders - only the stable sort preserves the alphabetical work already done.
💡
Key takeawayThis is exactly why `ORDER BY floor, name` needs a stable sort underneath it.
Department of Intelligent Computing

Common Mistakes

  • "All three sorts behave identically." They don't:
    bubble and insertion sort are adaptive (fast on nearly-sorted
    input), selection sort is not; selection sort makes exactly
    swaps no matter what, the others don't; only bubble and insertion
    sort are stable.
  • "Stability is just a technicality." It breaks multi-key sorting:
    the floor-then-name example above shows a real, working directory
    coming back with rooms out of alphabetical order on the same floor -
    the earlier sort's work gets silently undone.
  • "A loop invariant is just restating the loop." It must hold at a
    specific point every iteration and be strong enough that,
    combined with termination, it proves the exact claim you need - "the
    array looks more sorted each time" is not precise enough to prove
    anything.
Department of Intelligent Computing

Key Words Today

  • Multi-key sort: sorting by more than one field (e.g. floor,
    then building name) - where stability determines whether earlier
    sorts survive later ones.
  • Nearly-sorted input: an array only a few positions away from
    fully sorted - the case where adaptive sorts shine.
  • Counterexample: a single concrete input that disproves a general
    claim (e.g. [4a, 4b, 1c] disproving "selection sort is stable").
  • Collapse (at scale): when a technique that works fine on small
    input becomes impractically slow as input size grows - today's
    sorts, once the directory is campus-sized.
Department of Intelligent Computing

CampusNav: The Directory, Now Provably Sorted

Zooming back out to the running case study.
Wks 1-4
Unsorted directory, brute-force scan and recursion only
›
Wk 5 (today)
Small samples, sorted by hand-traced, provably correct methods
›
Wk 6
Full 1,200-entry directory, sorted fast enough to feel instant
›
Wk 7
Sorted directory enables binary search - "jump to room"

Today's three sorts are correct on the full directory too - they're
just not the ones CampusNav will actually ship with once it's
campus-sized.

Department of Intelligent Computing

Why Stability Shows Up in Real Products

This isn't only about CampusNav.

Spreadsheet "sort by column A, then column B" and SQL's ORDER BY col_a, col_b both rely on the first sort's order surviving the
second sort - that only works if the sorting method is stable.
Getting this wrong produces a list that "looks sorted" at a glance but
silently scrambles ties.

Every major standard library's default sort (Python's sorted, Java's Collections.sort) is guaranteed stable for exactly this reason - it's a documented correctness contract, not an implementation detail.
Department of Intelligent Computing

What Today's Three Sorts Cannot Do

These sorts are provably correct - we proved insertion sort correct on every input, not just the ones we traced. But all three are O(n^2) in the worst and average case. CampusNav's 40-room sample sorts instantly; its real 1,200-room directory noticeably lags; and the moment CampusNav adds partner campuses, at ~10,000 rooms, any of these three collapses. Correctness alone was never the whole goal - this was true from Week 1.
Department of Intelligent Computing

Next Week

Week 5 leaves basic sorts collapsing at scale unsolved. Week 6,
Advanced Sorting
, addresses it: merge sort and quicksort, both
on average, applied to CampusNav's full 1,200-entry
directory - the same jump from linear to logarithmic thinking you'll
soon recognize everywhere in this course.

Department of Intelligent Computing

Where This Week Lives in CLRS

A map, for anyone reading alongside the lectures.
Topic CLRS 4th ed
Insertion sort §2.1
Analyzing algorithms (worst/avg/best case, loop invariants) §2.2
Bubble sort Problem 2-2
Selection sort Exercise 2.2-2
  • If you want to go deeper: CLRS §2.3 previews divide-and-conquer
    and merge sort - one section ahead of where we are today, and
    exactly what Week 6 covers.
Department of Intelligent Computing

Where This Week Lives in CLRS, Continued

The loop-invariant proof style used on insertion sort today
(initialization / maintenance / termination) is the same shape CLRS
uses for correctness arguments throughout the book - Week 7 reuses
it, almost unchanged, for binary search.

Department of Intelligent Computing

Summary

  • Bubble, selection, insertion sort: all worst-case, but
    not interchangeable - only bubble and insertion are adaptive
    and stable; selection is neither.
  • Insertion sort is correct on every input, proven by a loop
    invariant with three parts (initialization, maintenance,
    termination) that will reappear all course.
  • Stability isn't cosmetic - it's what makes multi-key sorting (and
    every ORDER BY) work correctly.
  • Reminder: Assignment 1 due this week - submit before Week 6.
  • New: Week 5 Check - a short graded exercise on today's three
    sorts, released now, due before Week 6 begins (see
    materials/assignments/week05-check.html).
Department of Intelligent Computing

Summary, Continued

  • Reading: CLRS 4th ed, §2.1 (Insertion Sort) and §2.2 (Analyzing
    Algorithms); bubble sort is Problem 2-2, selection sort is Exercise
    2.2-2 - see the CLRS map above.
  • Prepare: think about why comparing neighbors (today) might be
    slower than splitting the array in half - guess for Week 6.
Department of Intelligent Computing

Thank You

Department of Intelligent Computing

SLOT 1: Title

notes: Welcome the class. Remind them Assignment 1 (Complexity & Pseudocode, released Week 3) is due this week - collect it at the start or confirm the submission deadline before diving in. Also flag the new Week 5 Check assignment, due before Week 6 begins.

SLOT 2: Where we are

notes: Point at Week 5. Say: "Five weeks in, CampusNav's directory is still just a pile of entries. Today we finally organize it - and prove our methods actually work." Also remind: Assignment 1 is due this week.

SLOT 3: Recap + open wound

NEW: Key Words Today, session 1

notes: Read each term aloud once. Tell them stability will look like a technicality until the counterexample lands, a few slides from now.

SLOT 4: The pain (Act 1 / MOTIVATE), zero jargon

notes: Do not say "sort" or "algorithm" yet. Describe the manual, repeated, error-prone re-ordering first - that's the setup for the next slide.

SLOT 5: Cost of not knowing

SLOT 6: Driving question

SLOT 7: Learning outcomes

SLOT 8: Origin

SLOT 9: Core concept

NEW: Key Words Today, session 2

notes: Read each term aloud. "Adaptive" is the word that will separate insertion sort from the other two on CampusNav's real workload - new rooms trickling in, not a full re-shuffle.

Act 3 / BUILD: Bubble sort. Idea + pseudocode merged into one slide.

NEW: dense worked example, bubble sort, simple tier

NEW: dense worked example, bubble sort, moderate tier (full trace + cost)

NEW: dense worked example, bubble sort, harder tier (adaptive/early-exit, absorbs old Check-Yourself)

NEW: dense worked example, bubble sort, the O(n^2) proof (flagship slide)

Act 3 / BUILD: Selection sort

NEW: dense worked example, selection sort, simple tier

NEW: dense worked example, selection sort, moderate tier

NEW: dense worked example, selection sort, harder tier (stability counterexample)

NEW: dense worked example, selection sort cost on every input (merges old check-yourself content)

Act 3 / BUILD: Insertion sort

NEW: dense worked example, insertion sort, simple tier

NEW: dense worked example, insertion sort, moderate tier (pass trace + microscope on one pass)

NEW: dense worked example, insertion sort, harder tier (best vs worst)

NEW: dense worked example, insertion sort correctness proof (flagship slide)

SLOT N-2: Worked example, CampusNav Ex 1 (insertion sort)

NEW: worked example, CampusNav Ex 2 (selection sort, contrast)

NEW: worked example, CampusNav Ex 3 (harder, stability payoff on real multi-key data)

SLOT N-1: Common mistakes

NEW: Key Words Today, session 3

notes: Read each term aloud. "Collapse at scale" is deliberately the same idea from Week 3's Big-O discussion - it's about to become this week's Limits slide, word for word.

SLOT N+1: Limits (Act 4 / CLOSE), becomes Week 6 slot 4

SLOT N+2: Bridge

NEW: CLRS reference slide, immediately before Summary

SLOT N+3: Summary

SLOT N+4: Thank You