Sorting

Implement Insertion Sort

Problem

Given a list of numbers, sort it using the Insertion Sort algorithm.

Example

{
"arr": [5, 8, 3, 9, 4, 1, 7]
}

Output:

[1, 3, 4, 5, 7, 8, 9]

Solution

function insertion_sort(arr) {
    // Write your code here.
    for(var i=1; i < arr.length; i++){
        var tempArr = arr[i];
        
        for(var j = i-1; j>=0 && arr[j] > tempArr; j--) {
            arr[j+1] = arr[j];
        }
        
        arr[j+1] = tempArr;
    }
    return arr;
}

Leave a comment