Ruby 冒泡排序

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

def bubbleSort(a)
  swapped = true
  while swapped == true
    i = 0
    swapped = false
    while(i < a.length-1):
      temp1 = a[i]
      temp2 = a[i+1]
      if (temp1 > temp2) then
        a[i], a[i+1] = temp2, temp1
        swapped = true
      end
      i += 1
    end
  end
  return a
end


#From here down is example usage of the function!

array = [1, 2, 6, 123, 32, -23, 2, -1, 2, 3, 123, 54]

puts "Before sorting:"
j = 0
while(j < array.length) #iterate through the loop, printing all values
  print array[j]
  print ' '
  j += 1
end
puts ""

bubbleSort(array)

puts "After sorting:"
k = 0
while(k < array.length)
  print array[k]
  print ' '
  k += 1
end