forked from thundergolfer/interview-with-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-sort.py
More file actions
77 lines (68 loc) · 2.06 KB
/
merge-sort.py
File metadata and controls
77 lines (68 loc) · 2.06 KB
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
73
74
75
76
77
import unittest
def mergesort_one(lst, show_trace=True):
if show_trace: print("Splitting ", lst)
if len(lst) > 1:
mid = len(lst) // 2
left_half = lst[:mid]
right_half = lst[mid:]
mergesort_one(left_half)
mergesort_one(right_half)
print("Merging ",left_half , right_half)
i=0
j=0
k=0
while i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
lst[k]=left_half[i]
i=i+1
else:
lst[k]=right_half[j]
j=j+1
k=k+1
while i < len(left_half):
lst[k]=left_half[i]
i=i+1
k=k+1
while j < len(right_half):
lst[k]=right_half[j]
j=j+1
k=k+1
return lst
def mergesort_two(lst):
result = []
if len(lst) < 2:
return lst
mid = len(lst) // 2
left = mergesort_two(lst[:mid])
right = mergesort_two(lst[mid:])
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] > right[j]:
result.append(right[j])
j += 1
else:
result.append(left[i])
i += 1
result += left[i:] # one of these will be empty so
result += right[j:] # we don't need to sort anymore
return result
# Unit Tests
class Test_Mergesort(unittest.TestCase):
def setUp(self):
pass
def test_mergesort_one(self):
self.assertEqual(
mergesort_one([1,5,6,8,9,2,3,4,7]), [1,2,3,4,5,6,7,8,9]
)
self.assertEqual(
mergesort_one([1,2,3,3,4,4,3,3,2,1]), [1,1,2,2,3,3,3,3,4,4]
)
def test_mergesort_two(self):
self.assertEqual(
mergesort_two([1,5,6,8,9,2,3,4,7]), [1,2,3,4,5,6,7,8,9]
)
self.assertEqual( mergesort_two([1]), [1] ) # edge case
self.assertEqual( mergesort_two([]), [] ) # edge case
self.assertEqual( mergesort_two([1,2,3,4,5]), [1,2,3,4,5] ) # already sorted case
if __name__ == '__main__':
unittest.main()