Skip to content

Instantly share code, notes, and snippets.

@ackintosh
Created August 18, 2013 06:41
Show Gist options
  • Select an option

  • Save ackintosh/6260245 to your computer and use it in GitHub Desktop.

Select an option

Save ackintosh/6260245 to your computer and use it in GitHub Desktop.
#gunmacs SelectionSort
require 'pry'
require 'test/unit'
class Array
def selection_sort
ary = self.dup
(0...size).each do |i|
min_index = i
((i + 1)...size).each do |j|
min_index = j if ary[i] > ary[j]
end
ary[i], ary[min_index] = ary[min_index], ary[i] if i != min_index
end
ary
end
end
class ArrayTest < Test::Unit::TestCase
def test_selection_sort
assert_equal([], [].selection_sort)
assert_equal([1], [1].selection_sort)
assert_equal([1, 2], [2, 1].selection_sort)
assert_equal([1, 2, 3, 4], [2, 4, 3, 1].selection_sort)
assert_equal([1, 2, 3, 4, 5], [5, 2, 4, 3, 1].selection_sort)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment