Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This is a bubble sort in ruby code simple and explained here.
# A method to define the bubble sort
def bubble_sort(array)
# condition: When array has more than one element
if array.count > 1
swap = true
# Loop: Run until swap is true
while swap
swap = false
# Loop: Run loop with array counts and swap if
(array.length-1).times do |z|
if array[z] > array[z+1]
# swap if current number element is greater than next number element.
array[z], array[z+1] = array[z+1], array[z]
# as we we have current number element is greater than next number element
# so we updated more swap needed.
swap = true
# While loop will stop once array[z] > array[z+1] will be false
# then swap will become false line number 8.
print "Befor sort - #{[7,9,3,5,4,2,1]}"
print "\n"
print "After sort - #{bubble_sort([7,9,3,5,4,2,1])}"
print "\n"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment