1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

マージソート

Posted at

基礎から学ぶデータ構造とアルゴリズム』「4.5 マージソート」の勉強メモです。自分なりに咀嚼したソート手順とサンプルコード(Ruby)をまとめています。

  1. 数字列を真ん中で二つの部分列に分割する
  2. 二つの部分列をそれぞれ整列する。これを再帰的に行う
  3. 整列済みの部分列をマージする
def merge_sort(a, n)
  return if n <= 1

  # a の前半をソート
  m = n / 2
  merge_sort a, m

  # a の後半を b にコピーしてソート
  b = a[m..(n - 1)]
  merge_sort b, n - m

  # a の前半を a の後半にコピー
  a[(n - m)..(n - 1)] = a[0..(m - 1)]

  # a の後半と b を大小比較しつつマージ
  ri = 0
  ai = n - m
  bi = 0
  while bi < n - m
    if ai < n && a[ai] <= b[bi]
      a[ri] = a[ai]
      ai += 1
    else
      a[ri] = b[bi]
      bi += 1
    end
    ri += 1
  end
end

a =  [10, 25, 75, 5, 30, 35, 15, 90, 65, 80, 50, 45]
merge_sort(a, a.size)
p a
[5, 10, 15, 25, 30, 35, 45, 50, 65, 75, 80, 90]

リンク

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?