Programming Language:
Javascript (JS)
Solution:
var insert = function(array, rightIndex, value)
{
for(var i = rightIndex; i >= 0 && array[i] > value; i--)
{array[i + 1] = array[i];}
array[i + 1] = value;
};
var insertionSort = function(array)
{
var len = array.length;
for(var i = 0; i < len-1; i++)
{insert(array, i, array[i+1]);}
};
var array = [22, 11, 99, 88, 9, 7, 42];
insertionSort(array);
println("Array after sorting: " + array);
Program.assertEqual(array, [7, 9, 11, 22, 42, 88, 99]);
var array = [2, 131, 99, 8218, -1, 0, 42];
insertionSort(array);
println("Array after sorting: " + array);
Program.assertEqual(array, [-1, 0, 2, 42, 99, 131, 8218]);