programming-examples/ruby/Algorithms/insertion_sort.rb

18 lines
382 B
Ruby
Raw Normal View History

2019-11-15 12:59:38 +01:00
# Insertion sort algorithm,
# uses N^2/4 compares and N^2/4 exchanges to sort a randomly ordered array,
# see test/insertion_sort_test.rb
module Insertion
def self.sort(array)
1.upto(array.size - 1) do |i|
j = i
while j > 0 && array[j] < array[j - 1]
array[j], array[j - 1] = array[j - 1], array[j]
j -= 1
end
end
array
end
end