State after inserting the 4th element
Warm-up · Trace the algorithm · about 4 min
Insertion sort runs on [6, 3, 8, 2, 7, 1]. Show the array right after the 4th element, 2, has been inserted into the sorted prefix. Then answer two questions about how 2 gets there.
Example 1
Input:
{"values":[6,3,8,2,7,1]}
Output:
[2,3,6,8,7,1]
Only the first four cells change; 7 and 1 wait for later passes.
Constraints
- The trace uses the input shown.
- Indices start at 0, so the 4th element is at index 3.
Learn the idea first: Insertion sort, a visual lesson.
More Insertion sort problems
- Implement insertion sort Standard
- Count the shifts Standard
- Spot the bug: the first cell Standard
- Insertion sort on a linked list Challenge