forked from nryoung/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_sort.py
More file actions
44 lines (31 loc) · 873 Bytes
/
Copy pathmerge_sort.py
File metadata and controls
44 lines (31 loc) · 873 Bytes
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
"""
merge_sort.py
Implementation of merge sort on a list and returns a sorted list.
Merge Sort Overview:
------------------------
Uses divide and conquer to recursively divide and sort the list
Time Complexity: O(n log n)
Space Complexity: O(n) Auxiliary
Stable: Yes
Psuedo Code: CLRS. Introduction to Algorithms. 3rd ed.
"""
def merge(left, right):
result = []
n, m = 0, 0
while n < len(left) and m < len(right):
if left[n] <= right[m]:
result.append(left[n])
n += 1
else:
result.append(right[m])
m += 1
result += left[n:]
result += right[m:]
return result
def sort(seq):
if len(seq) <= 1:
return seq
middle = int(len(seq) / 2)
left = sort(seq[:middle])
right = sort(seq[middle:])
return merge(left, right)