Merge Sort

/*
* Title: IMPLEMENTATION OF MERGESORT
* Name: Akshay Thakare
* Roll No: 6790
* SE COMPS
*/

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

void mergesort(int a[],int i,int j)
{
  int k;
  if(i<j)
  {
    k=(i+j)/2;
    mergesort(a,i,k);
    mergesort(a,k+1,j);
    merge(a,i,k,j);
  }
}

 void merge(int a[],int l,int m,int u)
 {
  int c[30];
  int i;
  int j;
  int k;

  i=l;
  j=m+1;
  k=0;

  while(i<=m&&j<=u)
  {
   if(a[i]<a[j])
   {
    c[k]=a[i];
    i++;
    k++;

   }
   else
   {
    c[k]=a[j];
    k++;
    j++;
   }
  }

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

  int main()
 {
   int a[30];
   int n;
   int i;
   printf("Enter number of entries into the array.Array size is 30\n");
   scanf("%d",&n);
   
   if(n<=30)
  {
   for(i=0;i<n;i++)
   {printf("Enter element number %d:\n",i+1);
    scanf("%d",&a[i]);
   }

   mergesort(a,0,n-1);
   printf("SORTED ARRAY\n");
   for(i=0;i<n;i++)
   {
    printf("%d \t",a[i]);
   }
  }
  else
  {
   printf("Enter a smaller size that is less than 30\n");
  }
return 0;
 }

/* OUTPUT:
-----------------------------------------------------------
  Enter number of entries into the array.Array size is 30
5
Enter element number 1:
4
Enter element number 2:
8
Enter element number 3:
21
Enter element number 4:
89
Enter element number 5:
388
SORTED ARRAY:
4       8       21      89      388  
-----------------------------------------------------------
Enter number of entries into the array.Array size is 30
67
Enter a smaller size that is less than 30
-----------------------------------------------------------
*/

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s