日本語

COMPARISON SORTS

Insertion Sort, visualised

Insertion sort takes the next element and inserts it into the correct place within the sorted part on its left, like arranging playing cards in your hand.

Run Insertion Sort in the visualizer →

Opens the Sorting Cinema visualizer with 16 elements in English.

How it works

  1. Treat the leftmost element as the sorted part.
  2. Take the next element and, while it is smaller than its left neighbour, swap it one step left.
  3. Stop when the left neighbour is not larger; the sorted part grows by one.
  4. Repeat until the last element.

Complexity and stability

Best
O(n)
Average
O(n²)
Worst
O(n²)
Extra space
O(1)
Stability
Stable

On nearly sorted input each element barely moves, approaching the best case of O(n). On reversed input every element travels to the front, giving O(n²).

Source of facts: Complexity follows the learning guide's comparison table and text, and this app's implementation.

Trace on a small array

The first operations on the input [5, 2, 4, 1, 3], following the same steps as the app.

#OperationArray after
1Swap [0]=5 and [1]=2[2, 5, 4, 1, 3]
2Swap [1]=5 and [2]=4[2, 4, 5, 1, 3]
3Swap [2]=5 and [3]=1[2, 4, 1, 5, 3]
4Swap [1]=4 and [2]=1[2, 1, 4, 5, 3]
5Swap [0]=2 and [1]=1[1, 2, 4, 5, 3]
6Swap [3]=5 and [4]=3[1, 2, 4, 3, 5]
7Swap [2]=4 and [3]=3[1, 2, 3, 4, 5]

In this trace, 7 compare / swap / write operations in total produce [1, 2, 3, 4, 5].

Suitable inputs and caveats

  • Strong on nearly sorted input; compare the “nearly sorted” and “reversed” presets.
  • This app visualises insertion as repeated swaps with the left neighbour.
  • Large random inputs lead to many comparisons and swaps.

FAQ

When is insertion sort fast?

On nearly sorted input. Each element moves only a short distance left, so the work approaches O(n).

Is insertion sort stable?

Yes. An element moves left only past strictly larger values, so equal values keep their order.