Skip to content

Instantly share code, notes, and snippets.

@davissp14
Created May 21, 2013 06:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davissp14/5617792 to your computer and use it in GitHub Desktop.
Save davissp14/5617792 to your computer and use it in GitHub Desktop.
Implementation of Insertion sort. Ascending / Descending
def insertion_sort(array)
for j in 1...array.length
i = j - 1
key = array[j]
while i >= 0 && array[i] > key
array[i+1] = array[i]
i = i - 1
end
array[i+1] = key
end
array
end
def reverse_insertion_sort(array)
for j in 1...array.length
i = j - 1
key = array[j]
while i >= 0 && array[i] < key
array[i+1] = array[i]
i = i - 1
end
array[i+1] = key
end
array
end
require 'test/unit'
class InsertionTest < Test::Unit::TestCase
def test_insertion_sort
assert_equal([2,3,4,4,6,8], insertion_sort([4,3,2,8,6,4]))
end
def test_reverse_insertion_sort
assert_equal([8,6,4,4,3,2], reverse_insertion_sort([4,3,2,8,6,4]))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment