Blowing Bubbles 2 takes this bubble sort:
a = ["e", "a", "c", "b", "d"]
b = 0
while b < a.length
c = 0
d = 1
while d < a.length
e = a[c]
f = a[d]
if f < e
a[c] = f
a[d] = e
end
c += 1
d += 1
end
b += 1
end
a
Through a series of transformations until it becomes this Bubble Sort:
class SortAlgorithms
class BubbleSort
attr_reader :array
def initialize(array)
@array = array
end
def sort
array.each { bubble_across }
array
end
def bubble_across
(array.length-1).times { |index| bubble_once index }
end
def bubble_once(index)
swap(index) if swap?(index)
end
def swap?(index)
array[index+1] < array[index]
end
def swap(index)
array[index], array[index+1] = array[index+1], array[index]
end
end
end
SortAlgorithms::BubbleSort.new(["e", "a", "c", "b", "d"]).sort
# => ["a", "b", "c", "d", "e"]
And then takes it back to the start. Here is a video of me going through it.