DEV Community

Code_Regina
Code_Regina

Posted on

Insertion Sort

                   -Insertion Sort: Introduction
                   -Insertion Sort: Implementation
Enter fullscreen mode Exit fullscreen mode

Insertion Sort: Introduction

Builds up the sort by gradually creating a larger left half which is always sorted.

Insertion Sort: Implementation

Insertion Sort Example


function insertionSort(arr){
    var currentVal;
    for(var i = 1; i < arr.length; i++){
        currentVal = arr[i];
        for(var j = i - 1; j >= 0 && arr[j] > currentVal; j--) {
            arr[j+1] = arr[j]
        }
        arr[j+1] = currentVal;
    }
    return arr;
}

insertionSort([2,1,9,76,4])


Enter fullscreen mode Exit fullscreen mode

Top comments (0)