-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsorts.py
72 lines (51 loc) · 1.63 KB
/
sorts.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
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
70
71
72
__author__ = "[email protected]"
"""
Merge Sort(Not in place)
(1) Divide and conquer Algorithm
Time Complexity : O( nlog(n) )
Space Complexity : O( nlog(n) )
GIST :
> Divide the array till you have one element
> Array of 1 element is sorted
> Merge Two Sorted arrays into a third sorted array
> Return new sorted array
"""
def merge_sort(arr):
"""
>>> merge_sort([3, 2, 1])
[1, 2, 3]
>>> merge_sort([6, 4, 3, 1, 2, 9])
[1, 2, 3, 4, 6, 9]
"""
if len(arr) < 2:
return arr
left, right = divide(arr)
left = merge_sort(left)
right = merge_sort(right)
return _merge(left, right)
def divide(arr):
return arr[:len(arr) // 2], arr[len(arr) // 2:]
def _merge(arr1, arr2):
"""
A linear time algorithm to merge two sorted lists
Complexity: Time Complexity Linear "Big-oh" O(m + n)
Where,
m = length of first list, and
n = length of second list
Space Complexity Linear same as above,
because we create a new third array of length: m + n
:post-condition: destroys the two input arrays
"""
new_array = []
while arr1 and arr2:
if arr1[0] <= arr2[0]:
new_array.append(arr1.pop(0))
else:
new_array.append(arr2.pop(0))
# if more elements in either array
new_array.extend(arr1)
new_array.extend(arr2)
return new_array
if __name__ == '__main__':
import doctest
doctest.testmod()