Created
May 3, 2011 18:12
-
-
Save brianstorti/953876 to your computer and use it in GitHub Desktop.
Bubble sort 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
# Bubble sort (inefficient for sorting large data volumes) | |
require 'test/unit' | |
def sort(a) | |
swapped = true | |
n = a.size | |
j = 0 | |
while swapped do | |
swapped = false | |
j += 1 | |
(n - j).times do |i| | |
if a[i] > a[i + 1] | |
a[i], a[i + 1] = a[i + 1], a[i] | |
swapped = true | |
end | |
end | |
end | |
a | |
end | |
class TestBubbleSort < Test::Unit::TestCase | |
def test_sort | |
arr = sort([6,3,5,2]) | |
assert_operator arr[0], :<, arr[1] | |
assert_operator arr[2], :<, arr[3] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment