Chapter 3 · Simulation

Sorting Properties Lab

← Chapter 3

Before · records (key, label)

After

Sorting Properties Lab

Using records with repeated keys, see whether a sorting algorithm preserves the original relative order of equal keys.

How to use

  • Pick an algorithm and press Sort. The records are sorted by their keys only; the label (A–F) just identifies each record.
  • The top row is the order before the run and the bottom row the order after. A line joins each record's old and new position; lines are coloured by key.
  • If the relative order of two records with the same key changes, that key's lines are drawn thick and dashed, and the result area says “Relative order changed”.
  • Reset restores the initial order: (3,A) (1,B) (3,C) (2,D) (1,E) (3,F). Running again on an already sorted row shows how the algorithm behaves on sorted input.

Stability

A sorting algorithm is stable if records with equal keys appear in the output in the same relative order as in the input. Stability matters when sorting by several keys one after another, for example first by name and then by grade.

  • Insertion sort in its standard form is stable (it shifts only when the key on the left is strictly greater) and in place.
  • Selection sort is usually in place but, in its standard swap-based form, not stable: a long-distance swap can make a record jump over another record with the same key.

A single input can only demonstrate instability; a “stable on this input” result does not prove that the algorithm is stable in general.

Counters

The comparison counter counts key comparisons. The second counter is the number of shifts in insertion sort and the number of swaps in selection sort.