Trace Insertion and Selection Sort
Core idea
Insertion sort extends a sorted prefix by shifting larger values right. Selection sort finds the smallest remaining item and swaps it into place. Both have quadratic worst-case comparisons; insertion can take linear time on already sorted input, whereas ordinary selection still scans every suffix. These examples mutate a list of comparable integers.
a = [5, 2, 4]for i in range(1, len(a)): x = a[i] j = i while j > 0 and a[j-1] > x: a[j] = a[j-1] j -= 1 a[j] = x print(a)Each pass leaves a sorted prefix; strict > preserves ties.
Selection swaps
a = [4, 3, 1, 2]for i in range(len(a)-1): m = i for j in range(i+1, len(a)): if a[j] < a[m]: m = j a[i], a[m] = a[m], a[i]print(a)The chosen minimum is fixed at each prefix boundary.
Common mistake
Ordinary selection sort is not stable: swapping a distant minimum can move equal-key records past one another.
Practice
Trace both algorithms on [3, 1, 2, 1]. Count key comparisons and writes separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Insertion and selection sort
Check your understanding of insertion and selection sort.
What is printed?
a=[2,1,3]a[0],a[1]=a[1],a[0]print(a)What is printed?
print(sum(range(4)))Best-case insertion comparisons on sorted input?
What breaks stability in ordinary selection sort?