Tuesday, October 14, 2008

Merge Sort

#include
#include
#include
class mergesort
{
public:
void sort(int *,int,int,int);
void pass(int *,int,int);
};
void mergesort::sort(int l[],int top,int size,int bottom)
{
int temp[10];
int f=top;
int s=size+1;
int t=top;
while((f<=size)&&(s<=bottom))
{
if(l[f]<=l[s])
{
temp[t]=l[f];
f++;
}
else
{
temp[t]=l[s];
s++;
}
t++;
}
if(f<=size)
{
for(f=f;f<=size;f++)
{
temp[t]=l[f];
t++;
}
}
else
{
for(s=s;s<=bottom;s++)
{
temp[t]=l[s];
t++;
}
}
for(int upper=top;upper<=bottom;upper++)
{
l[upper]=temp[upper];
}
}
void mergesort::pass(int append[],int m,int n)
{
if(m!=n)
{
int mid=(m+n)/2;
pass(append,m,mid);
pass(append,mid+1,n);
sort(append,m,mid,n);
}
}
void main()
{
int n,i;
mergesort s;
int list[100];
clrscr();
cout<<"enter size of list:";
cin>>n;
cout<<"enter the unsorted elements:";
for(i=0;i {
cin>>list[i];
}
cout<<"\n elements in list are";
for(i=0;i {
cout<<" "< }
i=0;
s.pass(list,i,n-1);
cout<<"\n merge sorted list is";
for(i=0;i {
cout<<" "< }
}

No comments: