5
5

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.

バブルソート

Last updated at Posted at 2015-03-10

隣り合うデータを比較して入れ替える

#
#  バブルソート
#
class Array
  def bubble_sort!
    # 配列のコピー
    array = self.dup
    # 配列の長さ分繰り返す
    (length-1).times do
      (length-1).times do |i|
        # 隣の要素と比較して入れ替える
        if array[i] > array[i+1]
          array[i + 1], array[i] = array[i], array[i + 1]
        end
      end
    end
    #元の配列をソート済みの配列に置き換える
    self.replace(array)
  end
end

p [10,2,5,3,6,9,1,4,7,8].bubble_sort!
# => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
5
5
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?