Monday, August 6, 2012

C++ Program for Mergesort


#include<iostream>
using namespace std;
int main()
{
void mergesort(int[],int,int);
int A[7]={1,2,5,3,7,6,4};
int low=0,high=6;
mergesort(A,0,6);
for(int i=low;i<=high;i++)
{
cout<<A[i]<<" ";
}
cout<<endl;
return 0;
}
void mergesort(int A[7],int low,int high)
{
if(low==high)
{
return;
}
int mid=(low+high)/2;
mergesort(A,low,mid);
mergesort(A,mid+1,high);
int a=low;
int b=mid+1;
int B[100],j=0;
while(a<=mid && b<=high)
{
if(A[a]<A[b])
{
B[j]=A[a];
j++;
a++;
}
else if(A[b]<A[a])
{
B[j]=A[b];
j++;
b++;
}
}
while(a<=mid)
{
B[j]=A[a];
j++;
a++;
}
while(b<=high)
{
B[j]=A[b];
j++;
b++;
}
int k=0;
for(int i=low;i<=high;i++)
{
A[i]=B[k];
k++;
}
}

No comments:

Post a Comment