Skip to content

Instantly share code, notes, and snippets.

@alexcambose
Created January 11, 2019 20:43
Show Gist options
  • Save alexcambose/a5ce5556eb58b538900d1f606ad1d6ee to your computer and use it in GitHub Desktop.
Save alexcambose/a5ce5556eb58b538900d1f606ad1d6ee to your computer and use it in GitHub Desktop.
JavaScript Insertion Sort
let array = [3,1,4,5,3,2,6];
for(let i = 1; i < array.length; i++) {
let j = i - 1; // array[0...i-1] is sorted
let temp = array[i];
while(j >= 0 && array[j] > temp) {
array[j+1] = array[j];
j--;
}
array[j+1] = temp;
}
console.log(array); // [1, 2, 3, 3, 4, 5, 6]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment