Created
March 28, 2016 15:41
-
-
Save thm-design/ad857d591cb08a50ed20 to your computer and use it in GitHub Desktop.
Insertion Sort Algorithm
This file contains hidden or 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
/* | |
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