Merge Sort


#include<stdio.h>
#include<sys/time.h>
void merqe_sort(int [],int,int);
void merqe(int [],int,int,int,int);
int main()
{
   int i,n,a[20];
   int t1,t2;
           
    struct timeval tt;
    struct timezone tz;

     printf("How many element you want to sort: ");
     scanf("%d",&n);

      printf("\nEnter the element: ");
      for(i=0;i<n;i++)
             scanf("%d",&a[i]);
 
      gettimeofday(&tt,&tz);
      t1=tt.tv_usec;
           
      merqe_sort(a,0,n-1);

      gettimeofday(&tt,&tz);
            t2=tt.tv_usec;
      for(i=0;i<n;i++)
            printf("%d ",a[i]);
           
             printf("\n\nTime required= %d",t2-t1);
             return 0;
}
void merqe_sort(int a[],int low,int high)
{
            int mid;
           
            if(low<high)
            {
                        mid=(low+high)/2;                 
                        merqe_sort(a,low,mid);
                        merqe_sort(a,mid+1,high);
                        merqe(a,low,mid,mid+1,high);
            }
}
void merqe(int a[],int low1,int high1,int low2,int high2)
{
            int i=low1,j=low2,k=0,temp[25];
           
            while(i<=high1 && j<=high2)
            {
                        if(a[i]<a[j])
                                    temp[k++]=a[i++];                 
                        else
                                    temp[k++]=a[j++];
            }
           
            while(i<=high1)
                        temp[k++]=a[i++];
            while(j<=high2)
                        temp[k++]=a[j++];
            for(i=low1,j=0;i<=high2;i++,j++)
                        a[i]=temp[j];
}

Output :-




No comments:

Post a Comment

ADA Programs

Home Bubble sort Insertion sort Selection sort Quick sort Merge sort Linear Search Binary Search Implementation and Time a...