Created
December 8, 2020 13:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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