Skip to content

Instantly share code, notes, and snippets.

@shihaohong
Created July 16, 2017 20:42
Show Gist options
  • Save shihaohong/7ff8277f4be84b54d5104340d884c647 to your computer and use it in GitHub Desktop.
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
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