Created
July 19, 2013 22:51
-
-
Save TGOlson/6042926 to your computer and use it in GitHub Desktop.
Simple bubble sort program, written in Ruby. Takes an array, and uses the bubble sort method to return a sorted array.
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
# Takes an array, and uses the bubble sort method to return a sorted array. | |
# bubble_sort([]) # .should == [] | |
# bubble_sort([1]) # .should == [1] | |
# bubble_sort([5, 4, 3, 2, 1]) # .should == [1, 2, 3, 4, 5] | |
def bubble_sort(arr) | |
sorted = false | |
while !sorted | |
out_of_place = 0 | |
i = 0 | |
while i < (arr.length - 1) | |
if arr[i] > arr[i+1] | |
arr[i], arr[i+1] = arr[i+1], arr[i] | |
out_of_place += 1 | |
end | |
i += 1 | |
end | |
if out_of_place == 0 | |
sorted = true | |
end | |
end | |
arr | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment