Last active
December 18, 2015 11:49
-
-
Save kimihito/5778453 to your computer and use it in GitHub Desktop.
バブルソート
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
#-*- coding: utf-8 -*- | |
def bubble_sort(arr) | |
if arr.nil? | |
return | |
end | |
n = arr.length | |
(n-1).downto(0).each do |i| | |
(1..i).each do |j| | |
if arr[j-1] > arr[j] | |
tmp = arr[j-1] | |
arr[j-1] = arr[j] | |
arr[j] = tmp | |
end | |
end | |
end | |
arr | |
end | |
arr = Array.new(100) | |
100.times do |i| | |
arr[i] = rand(100) | |
end | |
puts bubble_sort(arr) |
自己解決してたw
@hanachin さんにいつも聞いてるだけのクソ野郎から卒業します!!!
2013/06/18 二回目書いたけど、やっぱりsize - 1 を忘れてしまった…
2013/06/19 三回目アルゴリズム見ただけでも一応かけた
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
あー (0..i)の部分で arr[0-1] #=> arr[-1] が最初に比較対象になってしまったからそうなったのか…