我知道你正在學習Ruby和希望實現你自己的泡泡排序。 a.sort很簡單,但不會教你任何東西。我很高興你在幹什麼!你的氣泡排序方法有一個缺陷。你正在遞增我,並在每次迭代中將它用作數組的索引。它可能需要很多迭代才能完成,最糟糕的情況是需要n ** 2(n平方)的迭代,這明顯比數組中的元素多。但是,如果你的代碼按我期望的那樣工作,你預期它會運行,它只會對數組進行一次傳遞。
這是一個經典的紅寶石氣泡排序。 (讓用戶從控制檯填充數組) 請注意,我們將繼續處理整個陣列多次,直到我們不再需要交換任何值。
def bubble_sort(array)
n = array.length
puts "Sorting your array of #{n} items"
loop do #will loop forever till we break
#When we go through the entire array
#and don't have to swap then the array
#is sorted
swapped = false
(n-1).times do |i|
print "*" #just to illustrate how many iterations occur
if array[i] > array[i+1]
array[i], array[i+1] = array[i+1], array[i] #swap these values, no pesky temp variable
swapped = true
end
end
break if not swapped #we are done exit the loop
end
array #return the sorted array
end
puts "Amount of elements in your array"
n = gets.chomp.to_i
a = []
n.times do |num|
puts "input your element #{num}"
a <<gets.chomp.to_i
end
puts a
a = bubble_sort(a)
puts "Array sorted #{a}"
這裏是通過控制檯
Cyclops% ruby sort_test.rb
Amount of elements in your array
6
input your element 0
5465463
input your element 1
3421
input your element 2
432143
input your element 3
234123
input your element 4
645
input your element 5
1
5465463
3421
432143
234123
645
1
Sorting your array of 6 items
******************************
Array sorted [1, 645, 3421, 234123, 432143, 5465463]
Cyclops%
被運行在while循環的它的一個示例你有'溫度= A [1]'然後'A [1] = temp'其完成沒有。我想你想要'temp = a [i + 1]'a [i + 1] = a [i]''a [i] = temp',或者在更習慣的ruby中,a [i + 1] a [i] = a [i],a [i + 1]'。 – GSP
是的,我意識到我求助XD之後。 –