Merge Sort Algorithm

Merge Sort Algorithm

Merge Sort is a kind of Divide and Conquer algorithm in computer programrming. It is one of the most popular sorting algorithms and a great way to develop confidence in building recursive algorithms.
merge sort example

Divide and Conquer Strategy

Using the Divide and Conquer technique, we divide a problem into subproblems. When the solution to each subproblem is ready, we 'combine' the results from the subproblems to solve the main problem.
Suppose we had to sort an array A. A subproblem would be to sort a sub-section of this array starting at index p and ending at index r, denoted as A[p..r].
Divide
 
If q is the half-way point between p and r, then we can split the subarray A[p..r] into two arrays A[p..q] and A[q+1, r].
 
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]
 

The 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.
  1. MergeSort(A, p, r)
  2. If p > r
  3. return;
  4. q = (p+r)/2;
  5. mergeSort(A, p, q)
  6. mergeSort(A, q+1, r)
  7. merge(A, p, q, r)
To sort an entire array, we need to call MergeSort(A, 0, length(A)-1).
As shown in the image below, the merge sort algorithm recursively divides the array into halves until we reach the base case of array with 1 element. After that, the merge function picks up the sorted sub-arrays and merges them to gradually sort the entire array.
merge sort algorithm visualization

The merge step of merge sort

Every recursive algorithm is dependent on a base case and the ability to combine the results from base cases. Merge sort is no different. The most important part of the merge sort algorithm is, you guessed it, the "merge" step.
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 final sorted array.
Have we reached the end of any of the arrays?
    No:
        Compare current elements of both arrays 
        Copy smaller element into sorted array
        Move pointer of element containing smaller element
    Yes:
        Copy all remaining elements of non-empty array
merge two sorted arrays

Writing the code for merge algorithm

A noticeable difference between the merging step we described above and the one we use for merge sort is that we only perform the merge function on consecutive sub-arrays.
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 second subarray) and the last index of second subarray.
Our task is to merge two subarrays A[p..q] and A[q+1..r] to create a sorted array A[p..r]. So the inputs to the function are A, p, q and r
The merge function works as follows:
  1. Create copies of the subarrays L ← A[p..q] and M ← A[q+1..r].
  2. Create three pointers i,j and k
    1. i maintains current index of L, starting at 1
    2. j maintains current index of M, starting at 1
    3. k maintains current index of A[p..q], starting at p
  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]
  4. When we run out of elements in either L or M, pick up the remaining elements and put in A[p..q]
In code, this would look like:
  1. void merge(int A[], int p, int q, int r)
  2. {
  3. /* Create L ← A[p..q] and M ← A[q+1..r] */
  4. int n1 = q - p + 1;
  5. int n2 = r - q;
  6. int L[n1], M[n2];
  7. for (i = 0; i < n1; i++)
  8. L[i] = A[p + i];
  9. for (j = 0; j < n2; j++)
  10. M[j] = A[q + 1 + j];
  11. /* Maintain current index of sub-arrays and main array */
  12. int i, j, k;
  13. i = 0;
  14. j = 0;
  15. k = p;
  16. /* Until we reach either end of either L or M, pick larger among elements L and M and place them in the correct position at A[p..r] */
  17. while (i < n1 && j < n2)
  18. {
  19. if (L[i] <= M[j])
  20. {
  21. arr[k] = L[i];
  22. i++;
  23. }
  24. else
  25. {
  26. arr[k] = M[j];
  27. j++;
  28. }
  29. k++;
  30. }
  31. /* When we run out of elements in either L or M, pick up the remaining elements and put in A[p..r] */
  32. while (i < n1)
  33. {
  34. A[k] = L[i];
  35. i++;
  36. k++;
  37. }
  38. while (j < n2)
  39. {
  40. A[k] = M[j];
  41. j++;
  42. k++;
  43. }
  44. }

Merge function explained step-by-step

There is a lot happening in this function, so let's take an example to see how this would work.
As usual, a picture speaks a thousand words.
merging two consecutive subarrays of array
The array A[0..8] contains two sorted subarrays A[1..5] and A[6..7]. Let us see how merge function will merge the two arrays.
  1. void merge(int A[], int p = 1, int q = 4, int 6)
  2. {

Step 1: Create duplicate copies of sub-arrays to be sorted

  1. /* Create L ← A[p..q] and M ← A[q+1..r] */
  2. n1 = 4 - 1 + 1 = 4;
  3. n2 = 6 - 4 = 2;
  4. int L[4], M[2];
  5. for (i = 0; i < 4; i++)
  6. L[i] = A[p + i];
  7. /* L[0,1,2,3] = A[1,2,3,4] = [1,5,10,12] */
  8. for (j = 0; j < 2; j++)
  9. M[j] = A[q + 1 + j];
  10. /* M[0,1,2,3] = A[5,6] = [6,9]
create copies of subarrays for merging

Step 2: Maintain current index of sub-arrays and main array

  1. int i, j, k;
  2. i = 0;
  3. j = 0;
  4. k = p;
maintain indices of copies of sub array and main array

Step 3: Until we reach end of either L or M, pick larger among elements L and M and place them in the correct position at A[p..r]

  1. while (i < n1 && j < n2) {
  2. if (L[i] <= M[j]) {
  3. A[k] = L[i]; i++;
  4. }
  5. else {
  6. A[k] = M[j];
  7. j++;
  8. }
  9. k++;
  10. }
comparing individual elements of sorted subarrays until we reach end of one

Step 4: When we run out of elements in either L or M, pick up the remaining elements and put in A[p..r]

  1. /* We exited the earlier loop because j < n2 doesn't hold */
  2. while (i < n1)
  3. {
  4. A[k] = L[i];
  5. i++;
  6. k++;
  7. }
copy remaining elements from first array to main subarray
  1. /* We exited the earlier loop because i < n1 doesn't hold */
  2. while (j < n2)
  3. {
  4. A[k] = M[j];
  5. j++;
  6. k++;
  7. }
  8. }
copy remaining elements of second array to main subarray
This step would have been needed if size of M was greater than L.
At the end of the merge function, the subarray A[p..r] is sorted.

 

Comments

Popular posts from this blog

C Programming Tutorials

DataStructure and Algorithm

Java Programming Tutorial