forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort.rb
More file actions
36 lines (29 loc) · 744 Bytes
/
insertion_sort.rb
File metadata and controls
36 lines (29 loc) · 744 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# frozen_string_literal: true
# Sort an array using the InsertionSort algorithm
class InsertionSort
attr_reader :array_sorted
def initialize
@array_sorted = []
end
def init(array)
insertion_sort(array)
end
private
def insertion_sort(array, compare = ->(a, b) { a <=> b })
return nil if array.empty?
(1..array.length - 1).each do |i|
item = array[i]
index_hole = i
while index_hole.positive? && compare.call(array[index_hole - 1], item).positive?
array[index_hole] = array[index_hole - 1]
index_hole -= 1
end
array[index_hole] = item
end
@array_sorted = array
end
end
# test
i_s = InsertionSort.new
i_s.init([1, 4, 10, 2, 3, 32, 0])
p i_s.array_sorted