Insertion Sort visualization

Grow a sorted prefix by inserting each new value into its correct slot.

Like sorting playing cards in your hand: take the next card and slide it left past every larger card.

Very fast on nearly-sorted input (each value moves only a little), which is why hybrid sorts like Timsort use it for small runs.

Complexity

Time: best O(n), average O(n²), worst O(n²). Space: O(1). Difficulty: Beginner.

Pseudocode

procedure insertionSort(A):
  for i ← 1 to n−1:
    key ← A[i]; j ← i − 1
    while j ≥ 0 and A[j] > key:
      A[j+1] ← A[j]; j ← j − 1
    A[j+1] ← key
  return A

More sorting algorithms