For practice, I tried implementing Bubble sort in Ruby. I wasn't very sure how nested for loops would look like in Ruby. Is this the 'right way' to do this in Ruby? I found this question, but it looks much more complicated with stacks.
def bubble_sort(list)
n = list.length
n.downto(2) do |i|
0.upto(i-2) do |j|
if list[j] > list[j+1]
list[j],list[j+1] = list[j+1],list[j]
end
end
end
puts list
end
This is the code I wrote in Python which I then translated into Ruby code above.
def bubbleSort(alist):
n = len(alist)
for i in range(n, 1, -1):
for j in range(i-1):
if alist[j] > alist[j+1] :
alist[j],alist[j+1] = alist[j+1],alist[j]
for i in range(n-1)
repeatedly until nothing gets swapped. You get the same O(N^2) average and worst case, and it means you don't need therange(n, 1, -1)
, which is the easiest place to introduce bugs into your implementation. (The worst case is worse by a constant factor of 2 that way, but who cares? If you really want to trade simplicity for efficiency, why are you using bubblesort?) \$\endgroup\$