« Back to full matrix

Animated Sorting Algorithm Demo: Insertion Sort

Size:  20 · 30 · 40 · 50 ·
Algorithm:  Insertion · Selection · Bubble · Shell · Merge · Heap · Quick · Quick3

Algorithm

# move min to front, as sentinel
k = 1
for i = 2:n, if a[i] < a[k], k = i
swap a[1,k]
invariant: a[1] <= a[2..n]

# insertion sort with sentinel
for i = 2:n,
    for (k = i; a[k] < a[k-1]; k--) swap a[k,k-1]
    invariant: a[1..i] is sorted
end
        

Properties

Discussion

Although it is one of the elementary sorting algorithms with O(n2) worst-case time, insertion sort is the algorithm of choice either when the data is nearly sorted (because it is adaptive) or when the problem size is small (due to its low overhead). For these reasons, and because it is also stable, insertion sort is often used as the base case (when the problem size is small) for more complex algorithms that have higher overhead such as quicksort.

Directions

Key

References

Algorithms in Java, Parts 1-4, 3rd edition by Robert Sedgewick. Addison Wesley, 2003.