2:00am, Writing code

Roughly coding. Posted from Berlin.

BubbleSort in Javascript

特筆すべきところはないがプログラミング手習いとしてのバブルソート。一応お作法としてObject.assignを用いた非破壊的なソートにしている。

const a = [20, 1, 13, 2, 5, 3, 32, 11, 21];
console.log(bubbleSort(a)); // [ 1, 2, 3, 5, 11, 13, 20, 21, 32 ]

function bubbleSort(array) {
  const copy = Object.assign([], array);
  for (let i = 0; i < copy.length; i++) {
    for (let j = copy.length - 1; j > i; j--) {
      if (copy[j] < copy[j - 1]) {
        const tmp = copy[j - 1];
        copy[j - 1] = copy[j];
        copy[j] = tmp;
      }
    }
  }
  return copy;
}

参考

バブルソート - Wikipedia

プログラミングコンテスト攻略のためのアルゴリズムとデータ構造

プログラミングコンテスト攻略のためのアルゴリズムとデータ構造