-
Notifications
You must be signed in to change notification settings - Fork 595
/
merge_sort.py
40 lines (32 loc) · 1001 Bytes
/
merge_sort.py
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
class MergeSort(object):
def __init__(self, numbers):
self.values = numbers
self.count = len(numbers)
def sort(self):
self.merge_sort(0, self.count - 1)
return self.values
def merge_sort(self, low, high):
if low < high:
mid = (low + high) // 2
self.merge_sort(low, mid)
self.merge_sort(mid + 1, high)
self.merge(low, mid, high)
def merge(self, low, mid, high):
b = []
i = low
j = mid + 1
while i <= mid and j <= high:
if self.values[i] <= self.values[j]:
b.append(self.values[i])
i += 1
else:
b.append(self.values[j])
j += 1
while i <= mid:
b.append(self.values[i])
i += 1
while j <= high:
b.append(self.values[j])
j += 1
for index, val in enumerate(b):
self.values[low + index] = val