Insertion Sort Visualization
Speed:
Step: 0 / -1Algorithm Code
1function insertionSort(arr) {
2 const n = arr.length;
3
4 // Start from the second element
5 for (let i = 1; i < n; i++) {
6 // Element to be inserted
7 let key = arr[i];
8
9 // Position where element should be inserted
10 let j = i - 1;
11
12 // Move elements greater than key one position ahead
13 while (j >= 0 && arr[j] > key) {
14 arr[j + 1] = arr[j];
15 j--;
16 }
17
18 // Insert the key at the correct position
19 arr[j + 1] = key;
20 }
21
22 return arr;
23 }Visualization