forked from super30admin/PreCourse-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise_4.py
More file actions
52 lines (42 loc) · 1.25 KB
/
Exercise_4.py
File metadata and controls
52 lines (42 loc) · 1.25 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
def mergeSort(arr):
#write your code here
if len(arr) > 1:
mid = len(arr) // 2 # Find the middle of the array
left = arr[:mid] # Divide the array into two halves
right = arr[mid:]
# Recursive call on each half
mergeSort(left)
mergeSort(right)
# Merge the sorted halves
i = j = k = 0 # Initialize indices for merging
while i < len(left) and j < len(right):
if left[i] < right[j]:
arr[k] = left[i]
i += 1
else:
arr[k] = right[j]
j += 1
k += 1
# Check if any elements are left
while i < len(left):
arr[k] = left[i]
i += 1
k += 1
while j < len(right):
arr[k] = right[j]
j += 1
k += 1
# Code to print the list
def printList(arr):
for i in arr:
print(i)
#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)