Skip to content

Instantly share code, notes, and snippets.

@brianstorti
Created May 3, 2011 18:12
Show Gist options
  • Save brianstorti/953876 to your computer and use it in GitHub Desktop.
Save brianstorti/953876 to your computer and use it in GitHub Desktop.
Bubble sort in ruby
# 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