Created
January 29, 2019 14:05
-
-
Save bluurn/729e0c9267ca22e92467e664f6014263 to your computer and use it in GitHub Desktop.
JS: Implement Insertion Sort
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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