I am stuck on bubble_sort and I can’t seem to figure out why. The program loops continuously but when I compare my answer to the solution, they look virtually identical in theory. Could someone help me out here?
class Array
def bubble_sort!
# if self.empty? || self.length == 1
# return self
# end
sorted = false
while sorted == false
sorted = true
i = 0
while i < self.length-1
current_e = self[i]
next_e = self[i+1]
if current_e > next_e
sorted = false
current_e, next_e = next_e, current_e
end
i += 1
end
end
self
The line that now is:
current_e, next_e = next_e, current_e
needs to be:
self[i], self[i+1] = next_e, current_e
Otherwise you’re just endlessly swapping your temporary values current_e and next_e without ever modifying the original array.
–
Also, not to be schoolmarmish, but comments and tracking statements (I think that’s the right term) can really make your code easier to debug:
class Array
def bubble_sort!
if self.empty? || self.length == 1
return self
end # of edge-case detector
sorted = false
while sorted == false
sorted = true
puts "---"
i = 0
while i < self.length-1
current_e = self[i]
next_e = self[i+1]
puts "#{current_e} #{next_e}"
if current_e > next_e
sorted = false
self[i], self[i+1] = next_e, current_e
end # of swapping if-statement
i += 1
end # of i < self.length-1 loop
end # of "while sorted" loop
self # return sorted array
end # of bubble_sort method
end # of class Array definition
test_arr = [7,5,3,1,4,5,6]
test_arr.bubble_sort! # => [1, 3, 4, 5, 5, 6, 7]