Skip to content

Instantly share code, notes, and snippets.

@minsooshin
Last active July 6, 2016 05:24
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 minsooshin/d398f5da07dfdfd1cdd21608918ab790 to your computer and use it in GitHub Desktop.
Save minsooshin/d398f5da07dfdfd1cdd21608918ab790 to your computer and use it in GitHub Desktop.
Insertion Sort Algorithm
function insertSort(array) {
const n = array.length;
// loop from second element of array to last element
// because first element is first element of sorted portion
// at the beginning
for (let i = 1; i < n; i++) {
const element = array[i];
let j = i;
// shift the target element to the left
// until the target element is greater than left one
while (j > 0 && array[j - 1] > element) {
array[j] = array[j - 1];
j--;
}
array[j] = element;
}
return array;
}
console.log(insertSort([76, 23, 4, 7, 11]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment