1let insertionSort = (inputArr) => {
2 for (let i = 1; i < inputArr.length; i++) {
3 let key = inputArr[i];
4 let j = i - 1;
5 while (j >= 0 && inputArr[j] > key) {
6 inputArr[j + 1] = inputArr[j];
7 j = j - 1;
8 }
9 inputArr[j + 1] = key;
10 }
11 return inputArr;
12};
1const insertionSort = (inputArr) => {
2 const {length} = inputArr;
3 const retArray = inputArr;
4 for (let i = 1; i < length; i++) {
5 const key = inputArr[i];
6 let j = i - 1;
7 while (j >= 0 && inputArr[j] > key) {
8 retArray[j + 1] = inputArr[j];
9 j -= 1;
10 }
11 retArray[j + 1] = key;
12 }
13 return retArray;
14};
15insertionSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
1function insertionSort(inputArr) {
2 let n = inputArr.length;
3 for (let i = 1; i < n; i++) {
4 // Choosing the first element in our unsorted subarray
5 let current = inputArr[i];
6 // The last element of our sorted subarray
7 let j = i-1;
8 while ((j > -1) && (current < inputArr[j])) {
9 inputArr[j+1] = inputArr[j];
10 j--;
11 }
12 inputArr[j+1] = current;
13 }
14 return inputArr;
15}
1const insertionSort = array => {
2 const arr = Array.from(array); // avoid side effects
3 for (let i = 1; i < arr.length; i++) {
4 for (let j = i; j > 0 && arr[j] < arr[j - 1]; j--) {
5 [arr[j], arr[j - 1]] = [arr[j - 1], arr[j]];
6 }
7 }
8 return arr;
9};
10
11console.log(insertionSort([4, 9, 2, 1, 5]));
12