Insertion sort algorithm in JavaScript

algorithm
tomoyukikashiro
tomoyukikashiro

What is Insertion sort algorithm ?

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

http://en.wikipedia.org/wiki/Insertion_sort

Code

/***************************************
 * sort
 ***************************************/
var insertionSort = function(list){
  var length = list.length,
      i = 1,
      k,
      sortedIndex = 0,
      target,
      sorted;
  for(; i < length; i++){
    k = sortedIndex;
    target = list[i];
    sort: while(k >= 0){
      sorted = list[k];
      if(sorted < target){
        list.splice(i,1);
        list.splice(k+1,0,target);
        break sort;
      }
      --k;
      if(k < 0){
        list.splice(i,1);
        list.splice(0,0,target);
      }
    }
    console.log('processing... ' + list);
    ++sortedIndex;
  }
  return list;
};

/***************************************
 * main
 ***************************************/
var before = [0,9,3,4,6,7,8,2,1,5];
console.log('before : ' + before);

var after = insertionSort(before);
console.log('after : ' + after);

Test

/***************************************

  • main
    ***************************************/
    var before = [0,9,3,4,6,7,8,2,1,5];
    console.log(‘before : ’ + before);

var after = insertionSort(before);
console.log(‘after : ’ + after);

https://codepen.io/Tkashiro/embed/ZYEVay/?height=300&theme-id=9575&default-tab=result&embed-version=2