Skip to content

Instantly share code, notes, and snippets.

@thm-design
Created March 28, 2016 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thm-design/ad857d591cb08a50ed20 to your computer and use it in GitHub Desktop.
Save thm-design/ad857d591cb08a50ed20 to your computer and use it in GitHub Desktop.
Insertion Sort Algorithm
/*
Insertion sort
The idea here is that the beginning of your list is sorted and the everything else is assumed to be an unsorted mess.
The outer loop goes over the whole list, the index of which signifies where the "sorted" part of the list is. The inner
loop goes over the sorted part of the list and inserts it into the correct position in the array.
*/
var insertionSort = (nums) => {
for (let i = 1; i < nums.length; i++) {
for (let j = 0; j < i; j++) {
snapshot(nums);
if (nums[i] < nums[j]) {
let spliced = nums.splice(i, 1);
nums.splice(j, 0, spliced[0]);
}
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment