Skip to content

Instantly share code, notes, and snippets.

@adomokos
Created January 24, 2013 18:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adomokos/4626028 to your computer and use it in GitHub Desktop.
Save adomokos/4626028 to your computer and use it in GitHub Desktop.
Bubble Sorting in Ruby
module Enumerable
def bubble_sortit
reached_end = true
(1..self.length-1).each do |e|
if self[e] < self[e-1]
self[e-1], self[e] = self[e], self[e-1]
reached_end = false
end
end
bubble_sortit unless reached_end
self
end
end
describe "BubbleSort" do
it "swaps two elements" do
[3, 2, 5].bubble_sortit.should eq [2, 3, 5]
end
it "swaps three elements" do
[3, 2, 5, 4].bubble_sortit.should eq [2, 3, 4, 5]
end
it "swaps four elements" do
[3, 2, 5, 4, 5].bubble_sortit.should eq [2, 3, 4, 5, 5]
end
it "needs more swapping" do
[6, 5, 4].bubble_sortit.should eq [4, 5, 6]
end
it "does not change good order" do
[2, 3, 5].bubble_sortit.should eq [2, 3, 5]
end
it "sorts random elements" do
[3, 11, 54, 34, 28].bubble_sortit.should eq [3, 11, 28, 34, 54]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment