Skip to content

Instantly share code, notes, and snippets.

@kimihito
Last active December 18, 2015 11:49
Show Gist options
  • Save kimihito/5778453 to your computer and use it in GitHub Desktop.
Save kimihito/5778453 to your computer and use it in GitHub Desktop.
バブルソート
#!/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)
@kimihito
Copy link
Author

なんか配列の最後がうまく並んでないんだけどどうしてだろう…

@kimihito
Copy link
Author

これでいけた

@kimihito
Copy link
Author

あー (0..i)の部分で arr[0-1] #=> arr[-1] が最初に比較対象になってしまったからそうなったのか…

@hanachin
Copy link

自己解決してたw

@kimihito
Copy link
Author

@hanachin さんにいつも聞いてるだけのクソ野郎から卒業します!!!

@kimihito
Copy link
Author

2013/06/18 二回目書いたけど、やっぱりsize - 1 を忘れてしまった…

@kimihito
Copy link
Author

2013/06/19 三回目アルゴリズム見ただけでも一応かけた

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment