forked from kelvins/algorithms-and-data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.rb
50 lines (36 loc) · 901 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
# frozen_string_literal: true
# Sort an array using the MergeSort algorithm
class MergeSort
attr_reader :array_sorted
def initialize
@array_sorted = []
end
def init(array)
sort(array)
end
private
def sort(array)
return array if array.length <= 1
mid = (array.length / 2).round
left = array.take(mid)
right = array.drop(mid)
sorted_left = sort(left)
sorted_right = sort(right)
@array_sorted = merge(sorted_left, sorted_right)
end
def merge(left, right)
return left if right.empty?
return right if left.empty?
small_number = if left.first <= right.first
left.shift
else
right.shift
end
recursive = merge(left, right)
[small_number].concat(recursive)
end
end
# test
m = MergeSort.new
m.init([1, 4, 10, 2, 3, 32, 0])
p m.array_sorted