Room 9 of 14 · about 20 minutes

Selection sort

Selection sort is repeated minimum-finding, so it needs the minimum from room 7 and the swap from room 7.

Tasks checked0 of 4 XP earned on this path0

What this room checks you can do

Student can produce selection sort by composing the index-of-min loop with the three-statement swap, identify the invariant maintained by the outer loop's start index, and state the algorithm's O(n²) runtime.

Notes

Selection sort: find the min, swap it into position

Selection sort sorts an array in place by repeatedly finding the smallest remaining element and swapping it into the next "sorted" slot. The skeleton composes two patterns the course has already taught: the index-of-min variant of the best-so-far pattern, and the three-statement swap through a temporary variable.

public static void selectionSort(final int[] xs) {
    for (int start = 0; start < xs.length - 1; start++) {
        int minIdx = start;
        for (int i = start + 1; i < xs.length; i++) {
            if (xs[i] < xs[minIdx]) {
                minIdx = i;
            }
        }
        // swap xs[start] and xs[minIdx]
        final int temp = xs[start];
        xs[start] = xs[minIdx];
        xs[minIdx] = temp;
    }
}

Three structural commitments:

1. The outer loop's start is "where the next-smallest goes." On iteration 0, start is 0; the inner loop finds the minimum of the whole array and the swap moves it to position 0. On iteration 1, start is 1; the inner loop ignores position 0 (which already holds the minimum) and finds the minimum of xs[1..length-1]. The invariant: after the outer loop's k-th iteration completes, xs[0..k] is sorted and contains the k+1 smallest values. 2. The inner loop starts at start + 1, not 0. Comparing every iteration to the entire array would still produce a correct sort but would do redundant work: the slots [0..start) are already in their final positions. Skipping them is the algorithmic win that distinguishes selection sort from a naive "repeatedly sort the whole array" attempt. 3. The outer loop stops at xs.length - 1, not xs.length. Once xs.length - 1 slots are in place, the last slot necessarily holds the largest remaining value. A final iteration would compare it to itself; harmless but redundant.

Runtime

The inner loop runs n - 1, then n - 2, then n - 3, … iterations across the outer loop's lifetime. The total is n(n-1)/2, which is O(n²). Doubling the array size quadruples the runtime. Selection sort is asymptotically slower than the O(n log n) algorithms in java.util.Arrays.sort (which uses a tuned quicksort/mergesort hybrid), but its simplicity makes it the canonical first-sort to teach. CSCD 210 students implement it from scratch; production code uses Arrays.sort.

When to choose minIdx over min

The min value alone is enough to find the minimum, but selection sort needs the index of the minimum so the swap knows which slot to take from. Tracking minIdx lets the inner loop's if compare via xs[i] < xs[minIdx]: two array reads per iteration. The min-value variant int min = xs[start]; if (xs[i] < min) { min = xs[i]; minIdx = i; } is equivalent but doubles the bookkeeping.

In other languages

  • C: identical algorithm; the index-tracking pattern is universal.
  • Python: sorted(xs) and xs.sort() are built-ins (Timsort, O(n log n)); the selection-sort form is a teaching exercise only.
  • Java standard: Arrays.sort(int[]) (dual-pivot quicksort), Collections.sort(List<E>) (Timsort). Use these in production; never ship a hand-written selection sort.

What this room assumes you already have

Tasks

Do each one, then check the box. Checking a box is you saying you did it. You can uncheck a box if you check it by accident.

  1. trace
    Show the answer

    after pass 0 {1, 2, 8, 5, 9, 3} (1 swapped into slot 0); after pass 1 {1, 2, 8, 5, 9, 3} (2 already in place); after pass 2 {1, 2, 3, 5, 9, 8}; after pass 3 {1, 2, 3, 5, 9, 8}; after pass 4 {1, 2, 3, 5, 8, 9}.

  2. trace
    Show the answer

    pass 0 (start=0, minIdx=2, array {1, 3, 7, 5}); pass 1 (start=1, minIdx=1, array {1, 3, 7, 5}); pass 2 (start=2, minIdx=3, array {1, 3, 5, 7}).

  3. trace
    Show the answer

    a final, harmless iteration where the inner loop runs zero times and the swap exchanges xs[length-1] with itself.

  4. write
    Show the answer

    outer loop on start, inner loop finds minIdx, single swap(xs, start, minIdx); call after the inner loop.

Self check

Type what you think the answer is. Getting it wrong costs nothing and you can try as many times as you want.

Given int[] xs = {1, 2, 3, 4}; (already sorted), produce the trace.

Practice, untimed

Open this whenever you want, before the tasks or after them. Nothing in this section is recorded and nothing here is timed.

  1. Identify why the inner loop starts at start + 1 rather than 0.write
    Show the answer

    slots [0..start) are already in their final positions; revisiting them is wasted work and (more subtly) breaks the invariant about the "sorted prefix."

  2. Given the trace {5, 2, 8, 1, 9, 3} → {1, 2, 8, 5, 9, 3}, name the algorithmic moment.trace
    Show the answer

    end of selection sort's pass 0 (start=0, swap of xs[0] and xs[3]).

  3. Add a System.out.println(Arrays.toString(xs)) to the inside of the outer loop, after the swap. Predict what the program prints.write
    Show the answer

    one array snapshot per outer-loop iteration, matching the trace table.

How this room finishes

This room is done when all 4 tasks are checked and the self check is answered.