Sort Array Using Merge Sort Method.

Sort array using merge sort method

In this case,two sorted arrays are merged into third sorted array.

Basic method or algorithm

Suppose two numeric arrays contain m and n sorted values respectively srored from 0 to m-1 and 0 to n-1 locations.The name of first array is a and second array is b.Rusultant array

i=j=k=0;

while(i < m && j < n) do the following

begin

- if i th value of a is less than j th value of b then

-Copy i th value of a in k th position of c.

- increment i and k

-else if i th value of a is greater than ot equal to j th value of b then

-Copy j th value of b in k th position.

-increment j and k

end

-If first array is not terminated,then copy its remaining values into third array.

-If second array is not terminated,then copy its remaining values into third array.

#include < stdio.h >
#include < conio.h > 
void main()
{
        int a1[20],a2[20],a3[40];
        int max1,max2,max3;
        clrscr();
        printf("\nEnter max1: ");
        scanf("%d",&max1);
        read_data(a1,max1);
        printf("\nEnter max2: ");
        scanf("%d",&max2);
        read_data(a2,max2);
        max3=merge_sort(a1,a2,a3,max1,max2);
        printf("\nFirst array is \n");
        print_data(a1,max1);
        printf("\nSecond array is \n");
        print_data(a2,max2);
        printf("\nThird array is \n");
        print_data(a3,max3);
}
int read_data(int a[],int max)
{
        int i;
        printf("\nEnter %d sorted values \n",max);
        for(i=0;i < max;i++)
        {
                scanf("%d",&a[i]);
        }
        return;
}
int print_data(int a[],int max)
{
        int i;
        for(i=0;i < max;i++)
        {
                printf("%4d",a[i]);
        }
        return;
}
int merge_sort(a1,a2,a3,max1,max2)
int a1[],a2[],a3[];
int max1,max2;
{
        int i,j,k;
        i=j=k=0;
        while(i < max1 && j < max2)
        {
                if (a1[i] < a2 [j])
        {
                a3[k++]=a1[i++];
        }
        else
        {
                a3[k++]=a2[j++];
        }
        }
        while (i < max1)
        {
                a3[k++]=a1[i++];
        }
        while(j < max2)
        {
                a3[k++]=a2[j++];
        }
        return(k);
}