-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2-3-2-merge-sort-without-sentinel.rb
67 lines (48 loc) · 1.29 KB
/
2-3-2-merge-sort-without-sentinel.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
# http://en.wikipedia.org/wiki/Merge_sort
class MergeSort
class << self
def sort array
return array if array.length <= 1
left, right = [], []
middle = (array.length / 2).round
0.upto(middle - 1) { |i| left.push array[i] }
middle.upto(array.length - 1) { |i| right.push array[i] }
left = self.sort left
right = self.sort right
merge left, right
end
private
def merge left, right
result = []
i = 0
j = 0
0.upto(left.length + right.length - 1) do |k|
if i >= left.length
j.upto(right.length - 1) { |l| result.push right[l] }
return result
end
if j >= right.length
i.upto(left.length - 1) { |l| result.push left[l] }
return result
end
if left[i] <= right[j]
result[k] = left[i]
i += 1
else
result[k] = right[j]
j += 1
end
end
result
end
end
end
if $0 == __FILE__
require "test/unit"
class MergeSortTest < Test::Unit::TestCase
def test_sort
sorted_array = MergeSort.sort [6, 3, 1, 2, 4, 8, 7, 5]
assert_equal [1, 2, 3, 4, 5, 6, 7, 8], sorted_array
end
end
end