Insertion sort algorithm in JavaScript

November 17, 2014

Reading time ~2 minutes

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


/***************************************
 * 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);

See the Pen Insertion sort algorithm in JavaScrip by Tomoyuki kashiro (@Tkashiro) on CodePen.

add ticket number to git commit automatically

Most of ticket tracker like Github, pivotal tracker have function to connect your commit to ticket(story).But every time when you commit ...… Continue reading

I will build frontend and backend separately

Published on September 28, 2016

order of angular controller's initialisation

Published on October 05, 2015