Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manish-shrivastava/c857083e23cf14de0d767d4545f677f2 to your computer and use it in GitHub Desktop.
Save manish-shrivastava/c857083e23cf14de0d767d4545f677f2 to your computer and use it in GitHub Desktop.
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
end
end
end
# While loop will stop once array[z] > array[z+1] will be false
# then swap will become false line number 8.
end
array
end
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