It divides the input array into two halves, calls itself for the two halves, and then merges the two sorted halves. The merge() function is used for merging two halves. The merge(arr, l, m, r) is a key process that assumes that arr[l…m] and arr[m+1…r] are sorted and merges the two sorted sub-arrays into one. See the following C implementation for details.
MergeSort(arr[], l, r)
If r > l
- Find the middle point to divide the array into two halves:
middle m = l+ (r-l)/2 - Call mergeSort for first half:
Call mergeSort(arr, l, m) - Call mergeSort for second half:
Call mergeSort(arr, m+1, r) - Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
- Implementation:
Python program for implementation of MergeSort
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
Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
Driver 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)
Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Time Complexity: Sorting arrays on different machines. Merge Sort is a recursive algorithm and time complexity can be expressed as following recurrence relation.
T(n) = 2T(n/2) + θ(n)
The above recurrence can be solved either using the Recurrence Tree method or the Master method. It falls in case II of Master Method and the solution of the recurrence is θ(nLogn). Time complexity of Merge Sort is θ(nLogn) in all 3 cases (worst, average and best) as merge sort always divides the array into two halves and takes linear time to merge two halves.
Auxiliary Space: O(n)
Algorithmic Paradigm: Divide and Conquer
Sorting In Place: No in a typical implementation
Stable: Yes