Ready to begin
No records have been processed. Start with Next step.
![For input [14,4,22,11], each completed prefix is sorted: [14], [4,14], [4,14,22], [4,11,14,22].](/images/computational-thinking/week-6/sort-invariant.png)
Follow the selected procedure. Change a field, tie rule or weekday and explain why the result changes.
Ready
No records have been processed. Start with Next step.
Predict the next change. Keep track of which list level, field and position convention the procedure uses.
Procedure InsertionSort(L):
sortedList = []
foreach x in L:
sortedList = SortedListInsert(sortedList, x)
return sortedListAn invariant is a property maintained after each completed iteration. Here sortedList is sorted AND contains exactly the input occurrences processed so far. Initially [] satisfies both properties. A correct insertion adds one new occurrence while preserving sortedness.
When foreach ends, every input occurrence has been inserted, so the sorted output contains the complete input. This argument has an initial case, a preservation step and a final conclusion. It is stronger than saying the last displayed list “looks ordered”.
To reverse the sort direction, change x < z to x > z inside insertion. Reverse the key comparison, not the source record identities or the order of fields inside each pair.
Is “the result is sorted” a complete correctness claim?
No. An empty result is sorted but may have lost every input. You must also preserve all occurrences.
Why is an empty initial result useful?
It is already sorted, so it satisfies insertion’s precondition before the first call.
Which change produces descending order?
Insert before z when x > z instead of x < z.