Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions DataStructuresAndAlgorithms/Algorithms/python/MergeSort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Python program for implementation of Merge Sort

def mergeSort(arr):
if len(arr) > 1:

# Finding the mid of the array
mid = len(arr) // 2

# Dividing the array elements
L = arr[:mid] # into 2 halves
R = arr[mid:]

# Sorting the first half
mergeSort(L)

# Sorting the second half
mergeSort(R)

i = j = k = 0

# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1

# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1

while j < len(R):
arr[k] = R[j]
j += 1
k += 1


# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]

mergeSort(arr)

print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i])