insertino sort javascript code example
Example 1: Insertion Sort javascript
const insertionSort = (inputArr) => {
const {length} = inputArr;
const retArray = inputArr;
for (let i = 1; i < length; i++) {
const key = inputArr[i];
let j = i - 1;
while (j >= 0 && inputArr[j] > key) {
retArray[j + 1] = inputArr[j];
j -= 1;
}
retArray[j + 1] = key;
}
return retArray;
};
insertionSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])
Example 2: array sorting javascript insertion sort
function insertionSort(inputArr) {
let n = inputArr.length;
for (let i = 1; i < n; i++) {
let current = inputArr[i];
let j = i-1;
while ((j > -1) && (current < inputArr[j])) {
inputArr[j+1] = inputArr[j];
j--;
}
inputArr[j+1] = current;
}
return inputArr;
}