Created
March 17, 2013 14:21
-
-
Save ackintosh/5181717 to your computer and use it in GitHub Desktop.
Bubble sort in Ruby
This file contains hidden or 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
class Array | |
def bubble_sort | |
tmp = self.dup | |
res = [] | |
res.push tmp.bubbling until tmp.empty? | |
res | |
end | |
def bubbling | |
(length - 1).times do |i| | |
self[i], self[i+1] = self[i+1], self[i] if self[i] < self[i+1] | |
end | |
delete_at(-1) | |
end | |
end | |
p [3,1,5,6,10,9].bubble_sort | |
# [1, 3, 5, 6, 9, 10] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment