Javascript: Insertion Sort Implementation

Insertion sort has one outer loop and one inner loop. The first element in the list is considered sorted, thus, the outer loop starts from the second element to the end of the list. The inner loop starts from the current index-1 of the outer loop, and going backwards of the already sorted list until index 0 and inserts the value of the current outer index to the correct position of the already sorted elements. Each outer loop will increase the number of already sorted elements by 1, since each outer loop will insert the next element into the correct position of the already sorted elements.
Here is an example of insertion sort in Javascript

function insertionSort(data)
{
    var n=data.length;
    var next;
    for(var i=1; i<n; i++)//outer loop
    {
        next=data[i];
        for(var j=i-1; j>=0; j--)//inner loop
        {
            if( data[j] > next )//change > to < for descending order
            {
                data[j+1]=data[j]; // if data[j] is less than next, increase the position of data[j]
            }
            else
            {
                break; //else break out of the loop
            }
        }
        data[j+1]=next; // insert the next value to the correct postion of the already sorted elements
 
    }
 
    return data;
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search