Skip to content

Instantly share code, notes, and snippets.

@ValentynaGorbachenko
Created October 13, 2016 00:04
Show Gist options
  • Save ValentynaGorbachenko/f090ee591ac246fcf94e8c88659225c9 to your computer and use it in GitHub Desktop.
Save ValentynaGorbachenko/f090ee591ac246fcf94e8c88659225c9 to your computer and use it in GitHub Desktop.
insertion_sort created by ValentynaGorbachenko - https://repl.it/Dre9/1
// O(n^2) - time complexity
// O(1) - space complexity
// insertion sort
function insertionSort(arr){
// start loop from the second element in the Array
for (var i=1; i<arr.length; i++){
// store current elem
var temp = arr[i];
// start comparing current elem to the previous
var j=i-1;
// untill j>=0 or current elem less then previous elem
// reassign value of the next position of the after previous elem that was compared to current
// decrement j
while(temp<arr[j] && j>=0){
arr[j+1] = arr[j];
j--;
}
// assign current elem value to its rigth place
arr[j+1] = temp;
}
}
var a = [9,2,-1,32];
insertionSort(a);
console.log(a);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment