Click here to Skip to main content
15,885,914 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C#
#include<stdio.h>
#include<stdlib.h>

/* Merge Function for merging two subarrays*/
void Merge(int a[],int r,int lba,int b[],int s,int lbb,int c[],int lbc)
{
    int na=lba,nb=lbb,ptr=lbc,uba=lba+r-1,ubb=lbb+s-1,k;
    while(na<=uba && nb<=ubb)
    {
                  if(a[na]<b[nb])
                  {
                                 c[ptr]=a[na];
                                 ptr=ptr+1;
                                 na=na+1;
                  }
                  else
                  {
                                 c[ptr]=b[nb];
                                 ptr=ptr+1;
                                 nb=nb+1;
                  }
    }
    if(na>uba)
    {
              for(k=0;k<=ubb-nb;k++)
              c[ptr+k]=b[nb+k];
    }
    else
    {
        for(k=0;k<=uba-na;k++)
        c[ptr+k]=a[na+k];
    }
    return;
}

/*MergePass Function */
void MergePass(int a[],int n,int l,int c[])
{
     int q,s,r,lb,j;
     q=(int)(n/2*l);
     s=2*l*q;
     r=n-s;
     for(j=1;j<=q;j++)
     {
                     lb=(2*j-2)*l;
                     Merge(a,l,lb,a,l,lb+l,c,lb);
     }
     if(r<=l)
     {
             for(j=1;j<=r;j++)
             c[s+j]=a[s+j];
     }
     else
     {
             Merge(a,l,s+1,a,r,l+s+1,c,s+1);
     }
     return;
}

/*MergeSort function*/
void MergeSort(int a[],int n)
{
     int l,c[100];
     for(l=1;l<n;l=4*l)
     {
                       MergePass(a,n,l,c);
                       MergePass(c,n,2*l,a);
     }
}

/*Main (for getting input)*/
main()
{
      int i,a[100],n;
      printf("Enter the no. of elements\n");
      scanf("%d",&n);
      printf("Enter the array elements one by one\n");
      for(i=0;i<n;i++)
      scanf("%d",&a[i]);

      MergeSort(a,n);/*Call to MergeSort*/

      printf("Array after sorting using MergeSort Procedure\n");
      for(i=0;i<n;i++)
      printf("%d\t",a[i]);
      getch();
}
Posted
Updated 8-May-13 19:13pm
v4
Comments
Mehdi Gholam 9-May-13 1:11am    
Sounds like homework, try using a debugger.
Sergey Alexandrovich Kryukov 9-May-13 1:16am    
Use the debugger!
—SA
Brady Bar 9-May-13 1:16am    
debugger is reporting a access violation in line 12 c[ptr]=a[na].please help
Brady Bar 9-May-13 1:23am    
i am new to programming.so i don't exactly know how to use a debugger.please help..
CHill60 10-May-13 11:57am    
Depends on which version of C and which compiler / compile options you're using. Here's a general bit of help that covers the most common debuggers for Chttp://www.cprogramming.com/debuggers.html[^]

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900