Skip to content

Instantly share code, notes, and snippets.

@anshumanatri
Created March 12, 2009 10:17
Show Gist options
  • Save anshumanatri/78004 to your computer and use it in GitHub Desktop.
Save anshumanatri/78004 to your computer and use it in GitHub Desktop.
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
int a[10],c[10];
void merge(int , int , int );
void mergesort(int, int);
void main()
{
int n,i
;
clrscr();
cout<<"\n Enter the value of n:\t";cin>>n;
cout<"\n Enter the array:\t";
for(i=0;i<n;i++) scanf("%d",&a[i]);
mergesort(0,n-1);
cout<<"\n Element sorted using mergesort:\t";
for(i=0;i<n;i++) cout<<a[i]<<" ";
getch();
}
void merge(int low, int mid, int high)
{
int i=low,j=mid+1,k=low;
while(i<=mid && j<=high)
{
if(a[i]<a[j])
c[k++]=a[i++];
else
c[k++]=a[j++];
}
while(i<=mid) c[k++]=a[i++];
while(j<=high) c[k++]=a[j++];
for(int l=0;l<k;l++) a[l]=c[l];
}
void mergesort(int low, int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
mergesort(low,mid);
mergesort(mid+1,high);
merge(low,mid,high);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment