Merge Sort Algorithm
Merge Sort Algorithm
Merge Sort is one of the most popular sorting algorithms that is based on
the principle of Divide and Conquer Algorithm.
Divide
Conquer
In the conquer step, we try to sort both the subarrays A[p..q] and A[q+1,
r]. If we haven't yet reached the base case, we again divide both these
subarrays and try to sort them.
Combine
When the conquer step reaches the base step and we get two sorted
subarrays A[p..q] and A[q+1, r] for array A[p..r], we combine the results
by creating a sorted array A[p..r] from two sorted
subarrays A[p..q] and A[q+1, r].
MergeSort Algorithm
The MergeSort function repeatedly divides the array into two halves until
we reach a stage where we try to perform MergeSort on a subarray of size
1 i.e. p == r.
After that, the merge function comes into play and combines the sorted
arrays into larger arrays until the whole array is merged.
MergeSort(A, p, r):
if p > r
return
q = (p+r)/2
mergeSort(A, p, q)
mergeSort(A, q+1, r)
merge(A, p, q, r)
The merge step is the solution to the simple problem of merging two
sorted lists(arrays) to build one large sorted list(array).
The algorithm maintains three pointers, one for each of the two arrays and
one for maintaining the current index of the final sorted array.
No:
Yes:
This is why we only need the array, the first position, the last index of the
first subarray(we can calculate the first index of the second subarray) and
the last index of the second subarray.
3. Until we reach the end of either L or M, pick the larger among the
elements from L and M and place them in the correct position
at A[p..q]
int n1 = q - p + 1;
int n2 = r - q;
int i, j, k;
i = 0;
j = 0;
k = p;
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
k++;
arr[k] = L[i];
i++;
k++;
arr[k] = M[j];
j++;
k++;
The array A[0..5] contains two sorted subarrays A[0..3] and A[4..5]. Let us
see how the merge function will merge the two arrays.
int n1 = q - p + 1 = 3 - 0 + 1 = 4;
int n2 = r - q = 5 - 3 = 2;
int i, j, k;
i = 0;
j = 0;
k = p;
else {
arr[k] = M[j];
j++;
}
k++;
arr[k] = L[i];
i++;
k++;
}
Copy
the remaining elements from the first array to main subarray
arr[k] = M[j];
j++;
k++;
Copy remaining
elements of second array to main subarray
This step would have been needed if the size of M was greater than L.
#include <stdio.h>
int n1 = q - p + 1;
int n2 = r - q;
int i, j, k;
i = 0;
j = 0;
k = p;
arr[k] = L[i];
i++;
} else {
arr[k] = M[j];
j++;
k++;
arr[k] = L[i];
i++;
k++;
arr[k] = M[j];
j++;
k++;
// Divide the array into two subarrays, sort them and merge them
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
printf("\n");
// Driver program
int main() {
printArray(arr, size);