Insertion Sort Algorithm
A simple comparison-based sorting algorithm that builds the final sorted array one item at a time.
42
17
35
8
25
13
31
4
20
UnsortedSortedCurrent ElementComparing
1function insertionSort(arr) {
2 for (let i = 1; i < arr.length; i++) {
3 // Select element to be inserted
4 let key = arr[i];
5 let j = i - 1;
6
7 // Move elements greater than key
8 // to one position ahead
9 while (j >= 0 && arr[j] > key) {
10 arr[j + 1] = arr[j];
11 j--;
12 }
13
14 // Insert the key in its correct position
15 arr[j + 1] = key;
16 }
17 return arr;
18}