Sorting Algorithms· 15 min

Insertion Sort

Grow a sorted prefix by inserting each element

Setup

Size20
Step 1 / 398

Current step

1 / 398

Action: Starting Insertion Sort. We'll grow a sorted prefix by inserting each element into its correct spot.

Why: This is the next operation required by the algorithm.

Result: The visualization now reflects this operation.

Step log

18
9
36
17
25
6
29
11
53
59
51
32
40
52
37
9
12
57
55
53
012345678910111213141516171819
Unsorted
Comparing
Swap needed
Swapping
Moving
Pivot
Sorted
insertion.java
1void insertionSort(int[] arr) {
2 for (int i = 1; i < arr.length; i++) {
3 int key = arr[i];
4 int j = i - 1;
5 while (j >= 0 && arr[j] > key) {
6 arr[j + 1] = arr[j];
7 j--;
8 }
9 arr[j + 1] = key;
10 }
11}
● Java

Insertion Sort

Builds the final sorted array one element at a time by repeatedly taking the next element and inserting it into its correct position among previously sorted elements.

Time complexity
O(n²)
Space
O(1)
Stable
Yes
Comparisons
62
n = 201 / 398 steps