Method: Array#insertion_sort!

Defined in:
lib/array/sort/insertion_sort.rb

#insertion_sort!(&block) ⇒ Array

Sorts self in place, using insertion sort algorithm.

Comparisons for the sort will be done using the <=> operator or using an optional code block.

The block must implement a comparison between a and b and return an integer less than 0 when b follows a, 0 when a and b are equivalent, or an integer greater than 0 when a follows b.

The result is guaranteed to be stable. When the comparison of two elements returns 0, the order of the elements will be preserved.

Returns:



30
31
32
33
34
35
36
37
38
39
# File 'lib/array/sort/insertion_sort.rb', line 30

def insertion_sort!(&block)
  return self if length <= 1
  (1...length).each do |i|
    i.downto(1) do |j|
      break unless sort_compare(self[j - 1], self[j], &block) == 1
      swap(j - 1, j)
    end
  end
  self
end