Created
January 24, 2013 18:21
-
-
Save adomokos/4626028 to your computer and use it in GitHub Desktop.
Bubble Sorting in Ruby
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
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