Simple sort algorithm in JavaScript

November 16, 2014

Reading time ~2 minutes

What is Simple sort algorithm ?

  • if you want array to sort by ASC, you find minimum value in target list.
  • and pass it to new array from beginning.
  • this algorithm is slow to sort. so you had better to use this to large list.

Code

/***************************************
 * util
 ***************************************/
var getMin = function(list){
  var min = {
        index: 0,
        value: list[0]
      };
  list.forEach(function(target, index){
    if(target < min.value){
      min.index = index;
      min.value = target;
    } 
  });
  return min;
};
/***************************************
 * sort
 ***************************************/
var sortByMin = function(before){
  var min,
      after = [];
  
  while(before.length > 0){
    min = getMin(before);
    after.push(min.value);
    before.splice(min.index, 1);
  }
  return after;
};

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

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

Test

/***************************************
 * util
 ***************************************/
var getMin = function(list){
  var min = {
        index: 0,
        value: list[0]
      };
  list.forEach(function(target, index){
    if(target < min.value){
      min.index = index;
      min.value = target;
    } 
  });
  return min;
};
/***************************************
 * sort
 ***************************************/
var sortByMin = function(before){
  var min,
      after = [];
  
  while(before.length > 0){
    min = getMin(before);
    after.push(min.value);
    before.splice(min.index, 1);
  }
  return after;
};

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

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

See the Pen Simple 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