LoginSignup
4
4

More than 5 years have passed since last update.

挿入ソートを再帰で実装してみる

Last updated at Posted at 2014-11-07

前回のやつの再帰バージョン。

isort-mk2.js
function insert(x, xs) {
  if(xs.length <= 0) {
    return [x];
  }
  var y = xs.shift();
  if (x < y) {
    return [x].concat([y].concat(xs));
  } else {
    return [y].concat(insert(x, xs));
  }
}

function isort(xs) {
  if (xs.length <= 0) return xs;
  var x = xs.shift();
  return insert(x, isort(xs));
}
console.log(isort([4,3,5,2,1]));

追記

直しました。

4
4
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4