Insertion Sort builds a sorted array slice incrementally by picking unsorted elements and inserting them into their correct position within the sorted prefix.
Key = 11. Compare 11 with sorted prefix [12]. 12 > 11, shift 12 right and place 11 at index 0.
[12, 11, 13, 5, 6] -> Shift 12 -> Insert 11 -> [11, 12, 13, 5, 6]Key = 13. Compare 13 with 12. 13 > 12 -> 13 is already in correct position.
[11, 12, 13, 5, 6] -> No shift needed -> [11, 12, 13, 5, 6]Key = 5. Compare and shift 13, 12, 11 right. Place 5 at index 0.
[11, 12, 13, 5, 6] -> Shift [11,12,13] -> Insert 5 -> [5, 11, 12, 13, 6]Hold cards in one hand. Pick cards from the table one by one and slide each card into its correct spot among the cards in your hand.
250,000 steps (Quadratic)
O(N²) Quadratic Time
O(1) In-Place Space
Memory growth rate as N expands.
Relative efficiency rating for large N.
| Operation | Time Complexity | Space Complexity |
|---|---|---|
| Best Case (Nearly Sorted) | O(N) | O(1) |
| Worst Case | O(N²) | O(1) |
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let key = arr[i], j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}Powers small sub-array partitions in Python Timsort and C++ std::sort.
Sorts numbers arriving in real time.
Validate your conceptual understanding, operation mechanics, and core concepts of Insertion Sort.
Insertion Sort is stable, in-place, and faster than Quick Sort or Merge Sort for arrays with fewer than 16 elements!
Array loaded. Trigger Insertion Sort to visualize element shifting.