Merge Sort

Merge Sort is one of the most popular sorting algorithms that is based on the principle of Divide and Conquer Algorithm.

Here, a problem is divided into multiple sub-problems. Each sub-problem is solved individually. Finally, sub-problems are combined to form the final solution.

infix to postfix example

Divide and Conquer Strategy :

Using the Divide and Conquer technique, we divide a problem into sub-problems. When the solution to each subproblem is ready, we 'combine' the results from the sub-problems 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 sub-arrays A[p..q] and A[q+1, r]. If we haven't yet reached the base case, we again divide both these sub-arrays and try to sort them.

Combine

When the conquer step reaches the base step and we get two sorted sub-arrays 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 sub-arrays A[p..q] and A[q+1, r]

Algorithm

In the following algorithm, arr is the given array, beg is the starting element, and end is the last element of the array.

                MERGE_SORT(arr, beg, end)  
                
                if beg < end  
                set mid = (beg + end)/2  
                MERGE_SORT(arr, beg, mid)  
                MERGE_SORT(arr, mid + 1, end)  
                MERGE (arr, beg, mid, end)  
                end of if  
                
                END MERGE_SORT
            

The important part of the merge sort is the MERGE function. This function performs the merging of two sorted sub-arrays that are A[beg…mid] and A[mid+1…end], to build one sorted array A[beg…end]. So, the inputs of the MERGE function are A[], beg, mid, and end.

Program using C