Visualizers
Insertion Sort Visualizer
Step-through animation of Insertion Sort showing active elements shifting.
native (Canvas API)
Client-side
Ready to visualize.
Execution Log
Comparisons: 0
Swaps: 0
Current Action:
Idle
Legend:
Unsorted
Active Element
Shifting / Compare
Sorted Subarray
Insertion Sort Algorithm
Insertion Sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms like Quick Sort or Merge Sort.
How It Works
- Assume the first element is already sorted.
- Pick the next element (key) and compare it with elements in the sorted subarray (from right to left).
- Shift all elements that are greater than the key to the right.
- Insert the key at the correct index.
- Repeat until the array is fully sorted.
Implementation
function insertionSort(arr) {
const n = arr.length;
for (let i = 1; i < n; i++) {
const key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}