Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

posted at

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

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]));
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
4
Help us understand the problem. What are the problem?