Created
July 16, 2017 20:42
-
-
Save shihaohong/7ff8277f4be84b54d5104340d884c647 to your computer and use it in GitHub Desktop.
sorts an array in ascending order, taking into account the order of the numbers if the integer values matched
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
const insertionSort = function(array) { | |
// iterate through every element in the array | |
let temp; | |
for (let i = 1; i < array.length; i++) { | |
temp = array[i]; | |
let j = i; | |
while (j > 0 && ( (array[j - 1].value > temp.value) || ( (array[j - 1].value === temp.value) && (array[j - 1].order > temp.order)) ) ) { | |
array[j] = array[j - 1]; | |
j--; | |
} | |
array[j] = temp; | |
} | |
return array; | |
} | |
// insertionSort([{value: 10}, {value: 8, order: 2}, {value: 8, order: 1}, {value: 7}]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment