Program to sort given element using Merge Sort in C | Wave the world

Program to sort given element using Merge Sort in C

/*
   Merge Sort
   Created By: Pirate
*/

#include<stdio.h>
#include<conio.h>
void merge(int a[],int p,int q,int r);
void merge_sort(int a[],int p ,int r);
int main()
{
            int a[300],i,size;
            printf("** MERGE SORT **\n");
            printf("Enter the no. of elements\n");
            scanf("%d",&size);
            printf("Enter the %d elements.\n",size);
            for(i=0;i<size;i++)
            scanf("%d",&a[i]);
            merge_sort(a,0,size-1);
            printf("\n***********************************\n");
            printf("After Sorting\n");
            for(i=0;i<size;i++)
            printf("%d\t",a[i]);
            getch();
            return 0;
}
void merge_sort(int a[],int p,int r)
{
            int q;
            if(p<r)
            {
                        q=(p+r)/2;
                        merge_sort(a,p,q);
                        merge_sort(a,q+1,r);
                        merge(a,p,q,r);
            }
}
void merge(int a[],int p,int q,int r)
{
            int temp[300],i,j,k;
            i=p;
            j=q+1;
            k=p;
            while((i<=q) && (j<=r))
            {
                        if(a[i]<=a[j])
                        temp[k++]=a[i++];
                        else
                        temp[k++]=a[j++];
            }
            while(i<=q)
            temp[k++]=a[i++];
            while(j<=r)
            temp[k++]=a[j++];
            for(i=p;i<=r;i++)
            a[i]=temp[i];
}


Output




















0 comments:

Post a Comment

 

Pro

About