comp-psyche: MERGE SORT PROGRAM IN C

Thursday, 12 June 2014

MERGE SORT PROGRAM IN C

Here I am providing you with Merge Sort program in c.
#include<stdio.h> 

void mergesort(int a[],int i, int j); 
void merge(int a[],int p , int q, int r1); 

int main() 
{ 
 int a[20],i,n,item; 
 printf("Enter number of elements in array : "); 
 scanf("%d",&n);
  
 // Inputting elements
 for(i=0;i<n;i++) 
 { 
   printf("Enter number %d: ",i+1); 
   scanf("%d",&a[i]);
 } 
 
 // Displaying Elements before merge sort
 printf("Items in the array are : "); 
 for(i=0;i<n;i++)
 { 
   printf("%d ",a[i]); 
 } 
 
 //Applying merge sort
 mergesort(a,0,n-1); 
 
 // Displaying elements after merge sort
 printf("\nElements after merge sort : "); 
 for(i=0;i<n;i++) 
 { 
   printf("%d ",a[i]); 
 } 
 return 0; 
} 

void mergesort(int a[],int i, int j) 
{ 
 int mid; 
 if(i>=j) 
 return; 
 
 else 
 { 
   mid=(i+j)/2; 
   mergesort(a,i,mid); 
   mergesort(a,mid+1,j); 
   merge(a,i,mid,j);  
 } 
} 

void merge(int a[],int p , int q, int r) 
{ 
 int n1=q-p+1; 
 int n2=r-q;
 int left[n1+1];
 int right[n2+1]; 

 int i=0;
 int j=0;
 int k=0;
 
 
 for(i=0;i<n1;i++) 
 {
   left[i]=a[p+i]; 
 }
 
 for(i=0;i<n2;i++) 
 {
   right[i]=a[q+i+1];
 }
 
 left[n1]=9999; 
 right[n2]=9999;  
 
 i=0;
 j=0;
 
 for(k=p;k<=r;k++) 
 { 
 
   if(left[i]<right[j]) 
   { 
     a[k]=left[i]; 
     i++; 
   } 
 
   else 
   { 
     a[k]=right[j]; 
     j++; 
   } 
 } 
} 

No comments:

Post a Comment