-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmerge_sort.rb
80 lines (75 loc) · 1.46 KB
/
merge_sort.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
a = [15, 8, 4, 12, 4, 3, 8, 15, 10, 6, 2, -1, 0]
def merge_sort(a)
return a if a.length <= 1
middle = a.length / 2
left = a[0..middle - 1]
right = a[middle..-1]
puts "left: #{left}, right: #{right}"
left = merge_sort(left)
right = merge_sort(right)
merge(left, right)
end
def merge(left, right)
result = []
while left.size > 0 && right.size > 0
if left.first < right.first
result << left.shift
else
result << right.shift
end
p result
end
if left.empty?
result += right
else
result += left
end
result
end
p merge_sort(a)
# 'left: [15, 8, 4, 12, 4, 3], right: [8, 15, 10, 6, 2, -1, 0]
# left: [15, 8, 4], right: [12, 4, 3]
# left: [15], right: [8, 4]
# left: [8], right: [4]
# [4]
# [4]
# [4, 8]
# left: [12], right: [4, 3]
# left: [4], right: [3]
# [3]
# [3]
# [3, 4]
# [3]
# [3, 4]
# [3, 4, 4]
# [3, 4, 4, 8]
# [3, 4, 4, 8, 12]
# left: [8, 15, 10], right: [6, 2, -1, 0]
# left: [8], right: [15, 10]
# left: [15], right: [10]
# [10]
# [8]
# left: [6, 2], right: [-1, 0]
# left: [6], right: [2]
# [2]
# left: [-1], right: [0]
# [-1]
# [-1]
# [-1, 0]
# [-1]
# [-1, 0]
# [-1, 0, 2]
# [-1, 0, 2, 6]
# [-1]
# [-1, 0]
# [-1, 0, 2]
# [-1, 0, 2, 3]
# [-1, 0, 2, 3, 4]
# [-1, 0, 2, 3, 4, 4]
# [-1, 0, 2, 3, 4, 4, 6]
# [-1, 0, 2, 3, 4, 4, 6, 8]
# [-1, 0, 2, 3, 4, 4, 6, 8, 8]
# [-1, 0, 2, 3, 4, 4, 6, 8, 8, 10]
# [-1, 0, 2, 3, 4, 4, 6, 8, 8, 10, 12]
# [-1, 0, 2, 3, 4, 4, 6, 8, 8, 10, 12, 15]
# [-1, 0, 2, 3, 4, 4, 6, 8, 8, 10, 12, 15, 15]'