-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeSort.py
More file actions
84 lines (61 loc) · 1.74 KB
/
Copy pathmergeSort.py
File metadata and controls
84 lines (61 loc) · 1.74 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
78
79
80
81
82
83
def mergeSortDescending(list):
if len(list) <= 1:
return list
mid = len(list) // 2
leftHalf = list[:mid]
rightHalf = list[mid:]
left = mergeSortDescending(leftHalf)
right = mergeSortDescending(rightHalf)
return mergeDescending(left, right)
def mergeDescending(left, right):
newList = []
while left and right:
if left[0] > right[0]:
newList.append(left[0])
left.pop(0)
else:
newList.append(right[0])
right.pop(0)
if left:
newList.extend(left)
else:
newList.extend(right)
return newList
def mergeSortAscending(list):
if len(list) <= 1:
return list
mid = len(list) // 2
leftHalf = list[:mid]
rightHalf = list[mid:]
left = mergeSortAscending(leftHalf)
right = mergeSortAscending(rightHalf)
return mergeAscending(left, right)
def mergeAscending(left, right):
newList = []
while left and right:
if left[0] < right[0]:
newList.append(left[0])
left.pop(0)
else:
newList.append(right[0])
right.pop(0)
if left:
newList.extend(left)
else:
newList.extend(right)
return newList
def mergeSortAD(list, sort: bool):
sortType = sort
if sortType == True:
result = mergeSortAscending(list)
return result
elif sortType == False:
result = mergeSortDescending(list)
return result
else:
print("Please Input either 1 for Ascending Sort or 0 for Descending Sort")
l = [1 , 6, 32, 5, 12, 553, 132221, 33, 2, 4]
print(mergeSortDescending(l))
print(mergeSortAscending(l))
print(mergeSortAD(l, True))
print(mergeSortAD(l, False))