Skip to content

Instantly share code, notes, and snippets.

@TGOlson
Created July 19, 2013 22:51
Show Gist options
  • Save TGOlson/6042926 to your computer and use it in GitHub Desktop.
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.
# 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