Merge Sort
Merge Sort
Merge Sort
Difficulty Level : Medium ● Last Updated : 25 Jun, 2021
Like QuickSor t, Merge Sor t is a Divide and Conquer algorithm. It divides the input array
into two halves, calls itself for the two halves, and then merges the two sor ted 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 sor ted and merges the two
sor ted sub-arrays into one. See the following C implementation for details.
MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = l+ (r-l)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
The following diagram from wikipedia shows the complete merge sor t process for an
example array {38, 27, 43, 3, 9, 82, 10}. If we take a closer look at the diagram, we can see
that the array is recursively divided into two halves till the size becomes 1. Once the size
becomes 1, the merge processes come into action and star t merging arrays back till the
Recommended: Please solve it on “PR ACTICE” rst, before moving on to the solution.
C++
// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
for (auto i = 0; i < size; i++)
cout << A[i] << " ";
}
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
auto arr_size = sizeof(arr) / sizeof(arr[0]);
merge(arr, l, m, r);
}
}
/* UTILITY FUNCTIONS */
/* Function to print an array */
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]);
printf("\n");
}
/* Driver code */
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
Java
// Driver code
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
System.out.println("Given Array");
printArray(arr);
System.out.println("\nSorted array");
printArray(arr);
}
}
/* This code is contributed by Rajat Mishra */
P ython3
# into 2 halves
R = arr[mid:]
i = j = k = 0
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)
// A utility function to
// print array of size n */
static void printArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver code
public static void Main(String[] args)
{
int[] arr = { 12, 11, 13, 5, 6, 7 };
Console.WriteLine("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.Length - 1);
Console.WriteLine("\nSorted array");
printArray(arr);
}
}
Javascript
<script>
</script>
Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Time Complexity: Sor ting arrays on di erent machines. Merge Sor t is a recursive
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 Sor t is θ (nLogn) in all 3 cases (worst, average and
best) as merge sor t always divides the array into two halves and takes linear time to
Stable : Yes
1. Merge Sor t is useful for sor ting linked lists in O(nLogn) time. In the case of linked
lists, the case is di erent mainly due to the di erence in memor y allocation of arrays
and linked lists. Unlike arrays, linked list nodes may not be adjacent in memor y. Unlike
an array, in the linked list, we can inser t items in the middle in O(1) extra space and
O(1) time. Therefore, the merge operation of merge sor t can be implemented without
In arrays, we can do random access as elements are contiguous in memor y. Let us say
we have an integer (4-byte) array A and let the address of A[0] be x then to access
A[i], we can directly access the memor y at (x + i*4). Unlike arrays, we can not do
random access in the linked list. Quick Sor t requires a lot of this kind of access. In a
linked list to access i’th index, we have to travel each and ever y node from the head to
i’th node as we don’t have a continuous block of memor y. Therefore, the overhead
increases for quicksor t. Merge sor t accesses data sequentially and the need of
Merge sor t algorithm requires an additional memor y space of 0(n) for the temporar y
array.
It goes through the whole process even if the array is sor ted.
Merge Sort | GeeksforGeeks
Recent Ar ticles on Merge Sor t
3-way Merge Sor t, Selection Sor t, Bubble Sor t, Inser tion Sor t, Merge Sor t, Heap Sor t,
QuickSor t, Radix Sor t, Counting Sor t, Bucket Sor t, ShellSor t, Comb Sor t
Please write comments if you nd anything incorrect, or you want to share more
Attention reader! Don’t stop learning now. Get hold of all the impor tant DS A concepts
with the DSA Self Paced Course at a student-friendly price and become industr y ready.
To complete your preparation from learning a language to DS Algo and many more,
In case you wish to attend live classes with industr y exper ts, please refer DSA Live
Classes
Like 0
Next
QuickSort
Merge Sort with O(1) extra space merge and O(n lg n) time
01 06, Aug 18
Why Quick Sort preferred for Arrays and Merge Sort for Linked Lists?
02 16, May 15
GeeksforGeeks
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Load Comments
Practice Contribute
Courses Write an Article
Company-wise Write Interview Experience
Topic-wise Internships
How to begin? Videos