Skip to content

Instantly share code, notes, and snippets.

@ValentynaGorbachenko
Created October 13, 2016 00:04
Show Gist options
  • Select an option

  • Save ValentynaGorbachenko/f090ee591ac246fcf94e8c88659225c9 to your computer and use it in GitHub Desktop.

Select an option

Save ValentynaGorbachenko/f090ee591ac246fcf94e8c88659225c9 to your computer and use it in GitHub Desktop.

Revisions

  1. ValentynaGorbachenko created this gist Oct 13, 2016.
    25 changes: 25 additions & 0 deletions insertion_sort.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    // 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);