Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple sort algorithm in JavaScript #769

Open
tomoyukikashiro opened this issue Aug 1, 2022 · 0 comments
Open

Simple sort algorithm in JavaScript #769

tomoyukikashiro opened this issue Aug 1, 2022 · 0 comments

Comments

@tomoyukikashiro
Copy link
Owner


date: 2014-11-16
title: Simple sort algorithm in JavaScript
slug: simple-sort-algorithm-in-javascript
lang: en-US
tags: [algorithm]

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant