Bubble排序的ruby实现

阅读更多
list = [2, 5,  18, 8, 29, 10, 2, 9]


puts "before reorder: #{list.join(',')}"

def swap(list, i, j)
  tmp = list[i]
  list[i] = list[j]
  list[j] = tmp
end

list.each_with_index do |_, index|
  next if index == 0
  (index-1).downto(0).each do |j|
    if(list[j+1] > list[j])
      swap(list, j+1, j)
    else
      break
    end
  end
end

puts "after reorder: #{list.join(',')}"

 

你可能感兴趣的:(Ruby)