-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmerge_sort.rb
69 lines (61 loc) · 1013 Bytes
/
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
#
# Merge sort
#
# Created 2012/NOV/8
# Go Hosohara [email protected]
#
# Number of integer you will sort
Repeat = 100
# Sort data
$g_sort = []
#
# Merge sort
#
# Parameter: num int number of array
# offset int offset of sub array
def merge_sort(num,offset)
return if num <= 1
m = num/2
# Divide numbers
merge_sort(m,offset)
merge_sort(num-m,offset + m)
# Merge
buffer = []
i = 0
while i < m
buffer[i] = $g_sort[i+offset]
i += 1
end
j = m
i = k = 0
while i < m && j < num
if buffer[i] <= $g_sort[j+offset]
$g_sort[k+offset] = buffer[i]
k += 1
i += 1
else
$g_sort[k+offset] = $g_sort[j+offset]
k += 1
j += 1
end
end
while i < m
$g_sort[k+offset] = buffer[i]
k += 1
i += 1
end
end
#
#Main
#
# Create data
puts "Sort preparing..."
1.upto(Repeat){
$g_sort << rand(Repeat*10)
}
p $g_sort.join(" ")
puts "Sort begin"
merge_sort(Repeat,0)
puts "Sort end"
# Show sorted data
p $g_sort.join(" ")