Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created March 17, 2013 14:21
Show Gist options
  • Save ackintosh/5181717 to your computer and use it in GitHub Desktop.
Save ackintosh/5181717 to your computer and use it in GitHub Desktop.
Bubble sort in Ruby
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