Hi: I’m a complete beginner to Ruby. All I know is what I’ve read on
Chris P.'s web tutorial. I’m trying to write code to sort a sequence
of numbers using the bubble sort algorithm:
sequence = [4, 2, 3, 1]
class Array
def swap!(a,b)
self[a], self[b] = self[b], self[a]
self
end
end
checkE = [0]
checkS = [1]
while checkE != checkS
posn = sequence.length - 1
checkS = sequence
while posn > 0
if sequence[posn] < sequence[posn-1]
sequence.swap!(posn,posn-1)
end
posn = posn - 1
end
checkE = sequence
end
puts sequence.join(’, ')
I found the swap method online and just copied it, but it seems to work.
I’m trying to use checkS and checkE to see if the sequence is the same
after the bubble algorithm has run as it is at the beginning, since then
I know it’s finished. But I’m doing something wrong and I can’t figure
out what. It just runs through the algorithm and then stops, instead of
running the loop. I’m sure there is a much more sophisticated way to do
this, but I’d be really grateful if someone can point out what I’m doing
wrong in this code. Very many thanks in advance for any help.
Simon