-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathExercise_4.py
More file actions
52 lines (41 loc) · 1.03 KB
/
Copy pathExercise_4.py
File metadata and controls
52 lines (41 loc) · 1.03 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
# Python program for implementation of MergeSort
# [12, 11, 13, 5, 6, 7] 6
# left = [12, 11, 13]
# right= [5, 6, 7]
def mergeSort(arr):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
# left = [12, 11, 13]
left = mergeSort(nums[:mid])
# right= [5, 6, 7]
right= mergeSort(nums[mid:])
return merge(left, right)
# res = [11,12,13]
# left = [12]
# l
# right =[11,13]
# r
def merge(left,right):
res = []
l=r=0
while l < len(left) and r < len(right):
if left[l] < right[r]:
res.append(left[l])
l+=1
else:
res.append(right[r])
r+=1
res.extend(left[l:])
res.extend(right[r:])
# Code to print the list
def printList(arr):
#write your code here
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)