Insertion Sort List javascriot code example

Example 1: insertion sort js

let insertionSort = (inputArr) => {    let length = inputArr.length;    for (let i = 1; i < length; i++) {        let key = inputArr[i];        let j = i - 1;        while (j >= 0 && inputArr[j] > key) {            inputArr[j + 1] = inputArr[j];            j = j - 1;        }        inputArr[j + 1] = key;    }    return inputArr;};

Example 2: array sorting javascript insertion sort

function insertionSort(inputArr) {
    let n = inputArr.length;
        for (let i = 1; i < n; i++) {
            // Choosing the first element in our unsorted subarray
            let current = inputArr[i];
            // The last element of our sorted subarray
            let j = i-1; 
            while ((j > -1) && (current < inputArr[j])) {
                inputArr[j+1] = inputArr[j];
                j--;
            }
            inputArr[j+1] = current;
        }
    return inputArr;
}

Tags:

Java Example