Skip to content

Commit 63006e2

Browse files
committedOct 11, 2019
Created Merge Sort Scrip
1 parent d2ff15e commit 63006e2

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
 

‎merge_sort.py

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
# Python program for implementation of MergeSort
2+
# Merge Sort is a Divide and Conquer algorithm.
3+
# It divides input array in two halves, calls itself for the two halves
4+
# and then merges the two sorted halves.
5+
# The merge() function is used for merging two halves.
6+
7+
def mergeSort(arr):
8+
if len(arr) >1:
9+
mid = len(arr)//2 #Finding the mid of the array
10+
L = arr[:mid] # Dividing the array elements
11+
R = arr[mid:] # into 2 halves
12+
13+
mergeSort(L) # Sorting the first half
14+
mergeSort(R) # Sorting the second half
15+
16+
i = j = k = 0
17+
18+
# Copy data to temp arrays L[] and R[]
19+
while i < len(L) and j < len(R):
20+
if L[i] < R[j]:
21+
arr[k] = L[i]
22+
i+=1
23+
else:
24+
arr[k] = R[j]
25+
j+=1
26+
k+=1
27+
28+
# Checking if any element was left
29+
while i < len(L):
30+
arr[k] = L[i]
31+
i+=1
32+
k+=1
33+
34+
while j < len(R):
35+
arr[k] = R[j]
36+
j+=1
37+
k+=1
38+
39+
# Code to print the list
40+
def printList(arr):
41+
for i in range(len(arr)):
42+
print(arr[i],end=" ")
43+
print()
44+
45+
# driver code to test the above code
46+
if __name__ == '__main__':
47+
arr = [1, 12, 11, 2, 13, 5, 6, 7]
48+
print ("Given array is", end="\n")
49+
printList(arr)
50+
mergeSort(arr)
51+
print("Sorted array is: ", end="\n")
52+
printList(arr)

0 commit comments

Comments
 (0)
Please sign in to comment.