Saturday, September 3, 2011

Merge Sort


/* MERGE sort for numbers.Use step count,swap count,comparison count
*/

#include<stdio.h>
int stepcount=0,swapcount=0,compcount=0;

void mergesort(int a[] ,int i , int j);
void merge(int a[],int i1, int j1, int i2, int j2);


int main()
{
int a[50],n,i;
printf("\nEnter no of elements :");
scanf("%d",&n);
printf("\nEnter array elements :");
for(i=0;i<n;i++)
scanf("%d",&a[i]);

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

mergesort(a,0,n-1);

printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d   ",a[i]);
printf("\n No. of steps= %d",stepcount);
printf("\n No. of swaps= %d", swapcount);
printf("\n No. of comparisons= %d",compcount);

}

void mergesort(int a[] ,int i , int j)
   {
int mid;
if(i<j)
{ mid=(i+j)/2;
  mergesort(a,i,mid);    //left recursion
  mergesort(a,mid+1,j);  //right recursion
  merge(a,i,mid,mid+1,j); //meging of two sorted sub-arrays
}
    }


void merge(int a[],int i1, int j1, int i2, int j2)
  {
     int temp[50]; //array used for merging
     int i,j,k;
     i=i1; //beginning of the first list
     j=i2; //beginning of the second list
     k=0;
     while(i<=j1 && j <=j2) //while elemnts in both lists
      {
if(a[i]<a[j])
 {
  temp[k++]=a[i++];
  compcount++;
  stepcount+=2;
 }
else
 {
  temp[k++]=a[j++];
  compcount++;
  stepcount+=2;
 }
      }
    while(i<=j1) //copy remaining elements of the first list
      {
temp[k++]=a[i++];
swapcount++;
stepcount+=2;
      }
    while(j<=j2) //copy remaining elements of the second list
      {
temp[k++]=a[j++];
swapcount++;
stepcount+=2;
}

  //Transfer elemnts from temp[] back to a[]

    for(i=i1,j=0;i<=j2;i++,j++)
       a[i]=temp[j];
  }


No comments:

Post a Comment