-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertion_sort_archive3.rb
57 lines (51 loc) · 1.51 KB
/
insertion_sort_archive3.rb
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class InsertionSort
attr_reader :unsorted, :sorted, :array_length
def initialize(unsorted,sorted=[])
@unsorted = unsorted
@sorted = sorted
@array_length = unsorted.length
end
def move_to_sorted_array_and_remove_from_old_array(new_position)
sorted.insert(new_position,unsorted[0])
unsorted.shift
end
def sort
if array_length == 0
[]
else
move_to_sorted_array_and_remove_from_old_array(0)
if array_length >= 2
if (sorted[0] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(0)
else
move_to_sorted_array_and_remove_from_old_array(1)
end
end
if array_length >=3
if (sorted[0] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(0)
elsif (sorted[1] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(1)
else
move_to_sorted_array_and_remove_from_old_array(2)
end
end
if array_length >= 4
if
(sorted[0] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(0)
elsif
(sorted[1] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(1)
elsif
(sorted[2] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(2)
else
(sorted[3] <=> unsorted[0]) == 1
move_to_sorted_array_and_remove_from_old_array(3)
end
end
@sorted
end
end
end