Created
May 21, 2013 06:14
-
-
Save davissp14/5617792 to your computer and use it in GitHub Desktop.
Implementation of Insertion sort. Ascending / Descending
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
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