This is the first project of the main Ruby
curriculum at Microverse - @microverseinc
- Build a method
#bubble_sort
that takes an array and returns a sorted array using the bubble sort algorithm.
def bubble_sort(array)
sorting(array)
array
end
def sorting(array, &block)
index = array.length - 1
not_sorted = true
while not_sorted
not_sorted = false
(0...index).each do |i|
if block
next unless block.call(array[i], array[i + 1]).positive?
else
next unless array[i] > array[i + 1]
end
array[i], array[i + 1] = array[i + 1], array[i]
not_sorted = true
end
index -= 1
end
end
p bubble_sort([4, 3, 78, 2, 0, 2])
#=> [0,2,2,3,4,78]
- Build another method
#bubble_sort_by
which sorts an array by accepting a block. It raises a LocalJumpError error when no block is given.
def bubble_sort_by(array, &block)
raise LocalJumpError, 'no block given' unless block
sorting(array, &block)
array
end
bubble_sort_by(['hi', 'hello', 'hey']) do |left, right|
left.length <=> right.length
end
#=> ["hi", "hey", "hello"]