Tuesday, June 11, 2013

Sorting - Merge Sort tutorial

In previous tutorial , we have learned how to sort an array using Bubble Sort Algorithm   .

In this tutorial , we are going to learn how to make a sorted array using two unsorted arrays , using Merge Sort .

For this purpose , first we need to convert the two unsorted arrays to sorted arrays . For that you can use any Sorting Algorithm like Bubble Sort .

Next step is implemented using C as follows

#include <stdio.h>

int main()
{
    int a1[]  = {2,9,11,13,57};
    int a2[]  = {1,3,17,25,90};
    int i = 0, j = 0, k = 0 , t ;
    int a3[10];

    while(1)
    {

        if(a1[i] < a2[j])
        {
            a3[k++] = a1[i++];
            printf("\na3[%d] = %d",k-1,a3[k-1]);
        }

        else if(a2[j] < a1[i])
        {
            a3[k++] = a2[j++];
            printf("\na3[%d] = %d",k-1,a3[k-1]);
        }

        if(i == 5 || j == 5)
            break ;
    }

    for(;i<5;)
    {
        a3[k++] = a1[i++];
        printf("\na3[%d] = %d",k-1,a3[k-1]);
    }
    for(;j<5;)
     {
         a3[k++] = a2[j++] ;
        printf("\na3[%d] = %d",k-1,a3[k-1]);
     }
}