AiTechWorlds
AiTechWorlds
See Insertion Sort build the sorted prefix one element at a time, with live code highlight and step explanations.
def insertion_sort(a):
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = keyInsertion Sort builds the sorted array one element at a time, shifting larger elements right to insert each new value into its correct position.
| Best | O(n) |
| Average | O(n²) |
| Worst | O(n²) |
| Space | O(1) |
| Stable | Yes |
| In-place | Yes |
The Insertion Sort Visualizer animates how Insertion Sort works: it builds a sorted prefix one element at a time, shifting larger elements right to insert each new value into its correct position. Insertion Sort runs in O(n²) average/worst case, O(n) best case on nearly-sorted data, uses O(1) extra space, and is stable. Use Play, Step, and the timeline to follow each insertion.
Generate an array
Click New Array or set the size slider for a random dataset.
Play the animation
Press Play to watch the key element shift left into the growing sorted prefix.
Step and scrub
Use Step Forward/Back or the timeline to inspect each shift.
Read the synced code
The highlighted pseudocode line shows the current operation; switch tabs for C++, Java, Python, or JavaScript.
100% Private — No Server Required
All processing happens directly in your browser. No data is uploaded, stored, or transmitted to any server.
Last reviewed on June 14, 2026 by the AiTechWorlds Tools Team. All processing runs locally in your browser.