Insertion sort in JavaScript Here is a REPL of the code. The idea here is to learn how the basic insertion sort algorithm works rather than to use existing sort libraries.

How can it be clearer and more efficient?

function insertionSort(array)
{
    for(var i = 1; i &lt; array.length; ++i)
    {
        var currentItem = array[i];

        for(var j = i - 1; j &gt;= 0; --j)
        {
            if(array[j] &lt;= currentItem) break;
            array[j + 1] = array[j];
        }

        array[j + 1] = currentItem;
    }

    return array;
}

//test
var initialArray = [ 2, 4, 6, 8, 0, 5, 2, 5, 7, 8, 4, 7, 9 ];
var solutionArray = [ 0, 2, 2, 4, 4, 5, 5, 6, 7, 7, 8, 8, 9 ];

var sortedArray = insertionSort(initialArray);

var passed = JSON.stringify(sortedArray)==JSON.stringify(solutionArray);
console.log('passed:' + passed);
Eliminating some unnecessary code

Some programmers find break statements to be problematic. If you'd like to know more, here is a programmers stack exchange question about breaks and continues.

You could easily eliminate your use of break by just changing the inner loop to the following:

for (var j = i - 1; j &gt;= 0 &amp;&amp; array[j] &gt; currentItem; j--) {
  array[j + 1] = array[j];
}


This shortens your code a bit and condenses all the control flow logic of you loop into one spot.



You could shorten your code even further by eliminating the conditional j &gt;= 0:

for (var j = i - 1; array[j] &gt; currentItem; j--) {
  array[j + 1] = array[j];
}


However, this might obfuscate the code a bit.

Note: This works because array[-1] will return undefined and undefined &gt; myVar will always evaluate to false - ECMAScript Standard