-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathExercise_4.py
More file actions
70 lines (55 loc) · 1.66 KB
/
Exercise_4.py
File metadata and controls
70 lines (55 loc) · 1.66 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
# Python program for implementation of MergeSort
# Merge sort is also a devide and conqure approach. But in this the arrays are sorted during merging
# Basically we keep on deviding the arrays in half untill thhe last 2 elements are left 1 in left array
# and 2nd in right array. Then from that we start rebuilding the array by comparing the values in
# both subarray and assigning to the actual array
def mergeSort(arr, left=0, right=None):
if right == None:
right = len(arr) - 1
if left < right:
mid = (left+right)//2
mergeSort(arr, left, mid)
mergeSort(arr, mid+1, right)
merge(arr, left, mid, right)
def merge(arr, left, mid, right):
arr1 = []
arr2 = []
for i in range(left, mid+1):
arr1.append(arr[i])
for j in range(mid+1, right+1):
arr2.append(arr[j])
i = 0
j = 0
k=left
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
arr[k]=arr1[i]
i+=1
else:
arr[k] = arr2[j]
j+=1
k+=1
if i != len(arr1):
while i < len(arr1):
arr[k] = arr1[i]
i+=1
k+=1
if j != len(arr2):
while j < len(arr2):
arr[k] = arr2[j]
j+=1
k+=1
return
#write your code here
# Code to print the list
def printList(arr):
print(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)