Theory

Three algorithms in pseudocode

Three algorithms. You will not find code here — you will find what you need to write it.

Bubble sort

Walk the slice and swap every neighbouring pair that is out of order. After one pass the largest item is at the end. Repeat until a pass makes no swaps at all.

repeat:
    swapped ← false
    for i from 0 to end-1:
        cmp.Hit()
        if items[i].Title > items[i+1].Title:
            swap items[i] and items[i+1]
            swap.Hit()
            swapped ← true
    end ← end - 1
    if not swapped: stop

The swapped flag is not decoration: without it, bubble sort makes all n passes even over an already-sorted slice. With it, one.

Strictly >, never >=. Swapping equal items would destroy stability.

Selection sort

Find the smallest remaining item and swap it into place. Once per position.

for i from 0 to n-2:
    min ← i
    for j from i+1 to n-1:
        cmp.Hit()
        if items[j].Title < items[min].Title:
            min ← j
    if min ≠ i:
        swap items[i] and items[min]
        swap.Hit()

Notice that the inner loop always runs to the end. Sorted or not, there is no other way to know which remaining item is smallest. So selection sort has no best case, and the test demands exactly that.

In exchange you get one thing: at most n−1 swaps. Of the three, it moves the least data.

Insertion sort

Take each item in turn and shift it left until it sits in its place among the items already handled.

for i from 1 to n-1:
    cur ← items[i]
    j ← i - 1
    while j >= 0:
        cmp.Hit()
        if items[j].Title <= cur.Title: break
        items[j+1] ← items[j]
        swap.Hit()
        j ← j - 1
    items[j+1] ← cur

The line that matters is if items[j].Title <= cur.Title: break.

It stops the shifting the moment the place is found. If the slice is already sorted, every item needs exactly one comparison, and the whole sort costs n−1 comparisons and zero swaps.

That line is the point of this lesson. Remember it; step 6 shows what it is worth.

<=, not <. With <, equal items would still shift past each other and stability would be gone.

Stability

A sort is stable if equal keys keep their original relative order.

Bubble and insertion are stable because they only ever exchange neighbours: two equal items can never cross.

Selection sort is not. It throws an item across an arbitrary distance, and that jump can carry one equal item past another. The test asserts this: if your selection sort ever comes out stable, the test will say so — and then it is worth checking what that cost in swaps.