Algorithm Ruby

[Ruby] Bubble Sort - バブルソート

2017/02/17

メリークリスマス

今日はバブルソートをプレゼント(?)

[code lang="ruby"]
class Array
def swap!(a, b)
raise ArgumentError unless a.between?(0, self.count-1) && b.between?(0, self.count-1)

self[a], self[b] = self[b], self[a]

self
end

def swap(a, b)
self.dup.swap!(a, b)
end
end

array = [11, 13, 17, 19, 23, 29, 31]

p array

def sort_desc(end_i, array)
end_i.times do |i|
if array[i] < array[i+1]
array.swap!(i, i+1)
end
end
end

end_index = array.length - 1
array.each_with_index do |a, i|
sort_desc(end_index - i, array)
end

p array
[/code]

[code]
出力
[11, 13, 17, 19, 23, 29, 31]
[31, 29, 23, 19, 17, 13, 11]
[/code]

参考文献

Arrayを拡張したswap関数はここから引用
Rubyの配列でswap(入れ替え)メソッド

-Algorithm, Ruby