Quick actions

cmd+k|ctrl+k

Navigation

Languages

InsertionSort

Snippet info

Language

JavaScript

Visibility

public

Author

vinnysantos559

Created

2019-12-13T04:41:12Z

Updated

2019-12-13T04:41:12Z

const numbers = [99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0];

function insertionSort(array) {
    let length = array.length;
    let lastSortedIndex = 0;
    for(let i = 1; i < length; i++) {
        let curr = array[i];
        if(curr < array[lastSortedIndex]) {
            for(let j = 0; j <= lastSortedIndex; j++) {
                if(curr < array[j]) {
                    if(j === lastSortedIndex) {
                        array[i] = array[j];
                        array[j] = curr;
                        break;
                    }
                    else {
                        let replacedIndex = i;
                        let replacingIndex = lastSortedIndex;
                        while(replacingIndex>=j) {
                            array[replacedIndex] = array[replacingIndex];
                            replacedIndex--;
                            replacingIndex--;
                        }
                        array[j] = curr;
                        break;
                    }

                }
            }
        }
        lastSortedIndex++;
    }
}

insertionSort(numbers);
console.log(numbers);
INFO