Skip to content

Instantly share code, notes, and snippets.

@bluurn
Created January 29, 2019 14:05
Show Gist options
  • Save bluurn/729e0c9267ca22e92467e664f6014263 to your computer and use it in GitHub Desktop.
Save bluurn/729e0c9267ca22e92467e664f6014263 to your computer and use it in GitHub Desktop.
JS: Implement Insertion Sort
var insert = function(array, rightIndex, value) {
for(var j = rightIndex;
j >= 0 && array[j] > value;
j--) {
array[j + 1] = array[j];
}
array[j + 1] = value;
};
var insertionSort = function(array) {
for(var i = 1; i < array.length; i++) {
insert(array, i-1, array[i]);
}
};
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]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment