Skip to content

Instantly share code, notes, and snippets.

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