Created
May 3, 2011 14:41
-
-
Save brianstorti/953446 to your computer and use it in GitHub Desktop.
Insertion 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
# Insertion sort (inefficient on large lists) | |
require 'test/unit' | |
def sort(a) | |
n = a.size - 1 | |
1.upto(n) do |i| | |
new_value = a[i] | |
j = i | |
while j > 0 && a[j - 1] > new_value do | |
a[j] = a[j - 1] | |
j -= 1 | |
end | |
a[j] = new_value | |
end | |
a | |
end | |
class TestInsertionSort < Test::Unit::TestCase | |
def test_insertion_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