Thursday, September 21, 2017

C program for Non recursive(also called Bottom - up ) Merge sort.

#include<stdio.h>
#include<stdlib.h>

void merge(int*,int,int,int);
int mini(int x,int y);

main()
{
 int a[100],i,n,j;

 printf("Enter no.of elements\n");
 scanf("%d",&n);

 printf("Enter %d items\n",n);
 for(i=0;i<n;i++)
  scanf("%d",&a[i]);


/********  Non recursive (also called Bottom up) merge sort **********/
  for(i=1;i<n;i=2*i)
   for(j=0;j<n-i;j=j+2*i)
   merge(a,j,j+i-1,mini(j+2*i-1,n-1));

/**********************/


 for(i=0;i<n;i++)
  printf("%d\n",a[i]);


}


int mini(int x,int y)
{
 if(x<y) 
   return x; 
 else 
   return y;
}



void merge(int *a,int l,int m,int h)
{
 int i,j,k,temp[100];
 i=l;j=m+1;k=l;

 while(i<=m&&j<=h)
 {
  if(a[i]<a[j])
  {
  temp[k]=a[i];
  i++;
  k++;
  }
  else
  {
  temp[k]=a[j];
  j++;
  k++;
  }


 }
 while(i<=m)
 {
  temp[k]=a[i];
  i++;
  k++;
 }
 while(j<=h)
 {
  temp[k]=a[j];
  j++;
  k++;
  }

 for(i=l;i<=h;i++)
 a[i]=temp[i];

}

Comparison Merge Sort and Insertion Sort