Computer Science‎ > ‎

Arrays and Sorting: Merge Sort ( C Program/Java Program source code, a tutorial and an MCQ Quiz on Sorting)


Basic Sorting and Searching Algorithms for Arrays, at a glance

Merge Sort

To go through the C program and Java Program / source-code, scroll down to the end of this page


 


Merge Sort


Merge sort is based on Divide and conquer method. It takes the list to be sorted and divide it in half to create two unsorted lists. The two unsorted lists are then sorted and merged to get a sorted list. The two unsorted lists are sorted by continually calling the merge-sort algorithm; we eventually get a list of size 1 which is already sorted. The two lists of size 1 are then merged.

Algorithm:


This is a divide and conquer algorithm. This works as follows –

1. Divide the input which we have to sort into two parts in the middle. Call it the left part and right part.
Example: Say the input is -10 32 45 -78 91 1 0 -16 then the left part will be -10 32 45 -
78 and the right part will be 91 1 0 6.
2. Sort each of them separately. Note that here sort does not mean to sort it using some other method. We use the same function recursively.
3. Then merge the two sorted parts.

Input the total number of elements that are there in an array (number_of_elements). Input the array (array[number_of_elements]). Then call the function MergeSort() to sort the input array. MergeSort() function sorts the array in the range [left,right] i.e. from index left to index right inclusive. Merge() function merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right]. After merging output the sorted array.

MergeSort() function:

It takes the array, left-most and right-most index of the array to be sorted as arguments. Middle index (mid) of the array is calculated as (left + right)/2. Check if (left<right) cause we have to sort only when left<right because when left=right it is anyhow sorted. Sort the left part by calling MergeSort() function again over the left part MergeSort(array,left,mid) and the right part by recursive call of MergeSort function as MergeSort(array,mid + 1, right). Lastly merge the two arrays using the Merge function.

Merge() function: (Explained in greater detail within the tutorial document)

It takes the array, left-most , middle and right-most index of the array to be merged as arguments. 
Finally copy back the sorted array to the original array.

Properties:


Best case – When the array is already sorted O(nlogn).
Worst case – When the array is sorted in reverse order O(nlogn).
Average case – O(nlogn).
Extra space is required, so space complexity is O(n) for arrays and O(logn) for linked lists.



Merge Sort Visualization :

Here's a Java Applet Visualization which might help you get a clearer idea of what exactly happens in merge-sort.


Complete Tutorial :


                                                                                                                                        

Merge Sort - C Program Source Code


#include<stdio.h>
/*This is called Forward declaration of function */
void Merge(int * , int , int , int );
/* Logic: This is divide and conquer algorithm. This works as follows.
         (1) Divide the input which we have to sort into two parts in the middle. Call it the left part
              and right part.
             Example: Say the input is  -10 32 45 -78 91 1 0 -16 then the left part will be  
             -10 32 45 -78 and the right part will be  91 1 0 6.
         (2) Sort Each of them seperately. Note that here sort does not mean to sort it using some other
              method. We already wrote fucntion to sort it. Use the same.
         (3) Then merge the two sorted parts.
*/

/*This function Sorts the array in the range [left,right].That is from index left to index right inclusive
 */

void MergeSort(int *array, int left, int right)
{
        int mid = (left+right)/2;
        /* We have to sort only when left<right because when left=right it is anyhow sorted*/
        if(left<right)
        {
                /* Sort the left part */
                MergeSort(array,left,mid);
                /* Sort the right part */
                MergeSort(array,mid+1,right);
                /* Merge the two sorted parts */
                Merge(array,left,mid,right);
        }
}
/* Merge functions merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right].
 */

void Merge(int *array, int left, int mid, int right)
{
        /*We need a Temporary array to store the new sorted part*/
        int tempArray[right-left+1];
        int pos=0,lpos = left,rpos = mid + 1;
        while(lpos <= mid && rpos <= right)
        {
                if(array[lpos] < array[rpos])
                {
                        tempArray[pos++] = array[lpos++];
                }
                else
                {
                        tempArray[pos++] = array[rpos++];
                }
        }
        while(lpos <= mid)  tempArray[pos++] = array[lpos++];
        while(rpos <= right)tempArray[pos++] = array[rpos++];
        int iter;
        /* Copy back the sorted array to the original array */
        for(iter = 0;iter < pos; iter++)
        {
                array[iter+left] = tempArray[iter];
        }
        return;
}
int main()
{
        int number_of_elements;
        scanf("%d",&number_of_elements);
        int array[number_of_elements];
        int iter;
        for(iter = 0;iter < number_of_elements;iter++)
        {
                scanf("%d",&array[iter]);
        }
        /* Calling this functions sorts the array */
        MergeSort(array,0,number_of_elements-1);
        for(iter = 0;iter < number_of_elements;iter++)
        {
                printf("%d ",array[iter]);
        }
        printf("\n");
        return 0;
}


Merge Sort - Java Program Source Code

Post to LiveJournal
import java.io.*;
/* Logic: This is divide and conquer algorithm. This works as follows.
         (1) Divide the input which we have to sort into two parts in the middle. Call it the left part 
              and right part.
             Example: Say the input is  -10 32 45 -78 91 1 0 -16 then the left part will be  
             -10 32 45 -78 and the right part will be  91 1 0 6.
         (2) Sort Each of them seperately. Note that here sort does not mean to sort it using some other
              method. We already wrote fucntion to sort it. Use the same.
         (3) Then merge the two sorted parts.
*/
/*This function Sorts the array in the range [left,right].That is from index left to index right inclusive
 */
class MeregeSort
{
void MergeSort(int array[], int left, int right)
{
        int mid = (left+right)/2;
        /* We have to sort only when left<right because when left=right it is anyhow sorted*/
        if(left<right)
        {
                /* Sort the left part */
                MergeSort(array,left,mid);
                /* Sort the right part */
                MergeSort(array,mid+1,right);
                /* Merge the two sorted parts */
                Merge(array,left,mid,right);
        }
}
/* Merge functions merges the two sorted parts. Sorted parts will be from [left, mid] and [mid+1, right].
 */
void Merge(int array[], int left, int mid, int right)
{
        /*We need a Temporary array to store the new sorted part*/
        int tempArray[]=new int[right-left+1];
        int pos=0,lpos = left,rpos = mid + 1;
        while(lpos <= mid && rpos <= right)
        {
                if(array[lpos] < array[rpos])
                {
                        tempArray[pos++] = array[lpos++];
                }
                else
                {
                        tempArray[pos++] = array[rpos++];
                }
        }
        while(lpos <= mid)  tempArray[pos++] = array[lpos++];
        while(rpos <= right)tempArray[pos++] = array[rpos++];
        int iter;
        /* Copy back the sorted array to the original array */
        for(iter = 0;iter < pos; iter++)
        {
                array[iter+left] = tempArray[iter];
        }
        return;
}
int main()throws IOException
{
    BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        int number_of_elements;
        System.out.println("Enter the number of elements");
        number_of_elements=Integer.parseInt(in.readLine());
        int array[]=new int[number_of_elements]; 
        int iter;
        System.out.println("Enter the elements one by one");
        for(iter = 0;iter < number_of_elements;iter++)
        {
                array[iter]=Integer.parseInt(in.readLine());
        }
        /* Calling this functions sorts the array */
        MergeSort(array,0,number_of_elements-1); 
        for(iter = 0;iter < number_of_elements;iter++)
        {
                System.out.print(array[iter]+"\t");
        }
        System.out.print("\n");
        return 0;
}
}


MCQ Quiz: Efficient Sorting Algorithms- Quick sort, Merge Sort, Heap Sort- Check how much you can score!

Your score will be e-mailed to the address filled up by you.

MCQ Quiz- More efficient sorting algorithms


Related Tutorials :

Bubble Sort    

One of the most elementary sorting algorithms to implement - and also very inefficient. Runs in quadratic time. A good starting point to understand sorting in general, before moving on to more advanced techniques and algorithms. A general idea of how the algorithm works and a the code for a C program.

Insertion Sort

Another quadratic time sorting algorithm - an example of dynamic programming. An explanation and step through of how the algorithm works, as well as the source code for a C program which performs insertion sort. 

Selection Sort

Another quadratic time sorting algorithm - an example of a greedy algorithm. An explanation and step through of how the algorithm works, as well as the source code for a C program which performs selection sort. 

 Shell Sort

An inefficient but interesting algorithm, the complexity of which is not exactly known.

Merge Sort 

An example of a Divide and Conquer algorithm. Works in O(n log n) time. The memory complexity for this is a bit of a disadvantage.

Quick Sort

In the average case, this works in O(n log n) time. No additional memory overhead - so this is better than merge sort in this regard. A partition element is selected, the array is restructured such that all elements greater or less than the partition are on opposite sides of the partition. These two parts of the array are then sorted recursively.

Heap Sort

 Efficient sorting algorithm which runs in O(n log n) time. Uses the Heap data structure. 

Binary Search Algorithm

 Commonly used algorithm used to find the position of an element in a sorted array. Runs in O(log n) time. 





Merge Sort Visualization :

Here's a Java Applet Visualization which might help you get a clearer idea of what exactly happens in merge-sort.
 



Testing Zone For Programmers- 

 

Try out our online Multiple-Choice-Question tests in Programming and Computer Science!


 

Photo-credits: www.istockphoto.com

 
 Quizzes on Basic Object Oriented Programming with C++   Quizzes on Java Programming
  
 Quizzes on C Programming- Arrays, Strings and Pointers
  1. C Programming MCQ Quiz #1:  Strings- 1
  2. C Programming MCQ Quiz #2: Strings (2)
  3. C Programming MCQ Quiz #3: Strings (3)
  4. C Programming MCQ Quiz #4: Arrays(1)
  5. C Programming MCQ Quiz #5: Arrays (2)
  6. C Programming MCQ Quiz #6: Arrays (3)
  7. C Programming MCQ Quiz #7: Pointers (1)
  8. C Programming MCQ Quiz #8: Pointers (2)
 Quizzes on Data Structures, Algorithms and Complexity
  1. MCQ Quiz #1: The Basics of Sorting Algorithms- Quadratic Sorts
  2. MCQ Quiz #2: Efficient Sorting Algorithms- Quick sort, Merge Sort, Heap Sort
  3. MCQ Quiz #3- The Radix Sort
  4. MCQ Quiz #4: Divide and Conquer Techniques- Binary Search, Quicksort, Merge sort, Complexities
  5. MCQ Quiz #5- Dynamic Programming
  6. MCQ Quiz #6- Complexity of Algorithms
  7. MCQ Quiz #7- Application of Master's Theorem
  8. MCQ Quiz #8: Binary Search Trees
  9. MCQ Quiz #9: B-Trees
  10. 10 MCQ Quiz #9: AVL-Trees
  11. 11 MCQ Quiz #10: Representing Graphs as Data Structures
  12. 12 MCQ Quiz #11: Spanning Trees
  13. 13 MCQ Quiz #12: Algorithms - Graphs: Spanning Trees - Kruskal and Prim Algorithms
  14. 14 MCQ Quiz #13: Algorithms - Graphs: Depth and Breadth First Search