Quick actions

cmd+k|ctrl+k

Navigation

Languages

Insertion Sort

Snippet info

Language

JavaScript

Visibility

public

Author

saurabhtiwari75844

Created

2023-03-16T15:12:39.798143Z

Updated

2023-03-16T15:12:39.798143Z


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

function InsertionSort(array) {
    const length = array.length;
    for(let i=0; i < length; i++) {
        if(array[i] < array[0]) {
            //move number to the first position
            array.unshift(array.splice(i,1)[0]);
        } else {
            // find where the number should go
            for(let j=1; j < i; j++) {
                if(array[i] > array[j-1] &&  array[i] < array[j])
                {
                    // move to the right spot
                    array.splice(j,0, array.splice(i,1)[0]);
                }
            }
        }
    }
}

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