4
4

More than 5 years have passed since last update.

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

Posted at

Wikipediaの挿入ソートのC言語サンプルをそのままちょくやくしただけ。

キモはwhile部分。挿入したい要素以外の要素を後ろにずらし、x[j - 1] > tmpの時点で終了して要素をそこにぶっこむ。

function isort(x) {
  for (var i = 1; i < x.length; i++) {
    var tmp = x[i];
    if (x[i - 1] > tmp) {
      var j = i;

      while (j > 0 && x[j - 1] > tmp) {
        x[j] = x[j - 1];
        // console.log("tmp: ", tmp, "x[j]: ", j, x[j]);
        j--;
      }
      x[j] = tmp;
    }
  }
  return x;
}
console.log(isort([4,3,5,2,1]));
4
4
0

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