归并排序
一.实现
1)第一种写法:
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
#define LENGTH 15
void Merge(int a[],int left,int right,int rightend)
{
int leftend=right-1;
int n1=leftend-left+1;
int n2=rightend-right+1;
int *tempArrayA=(int*)malloc(sizeof(int)*n1);
int *tempArrayB=(int*)malloc(sizeof(int)*n2);
for(int i=0;i<n1;i++)
tempArrayA[i]=a[left+i];
for(i=0;i<n2;i++)
tempArrayB[i]=a[right+i];
int alongA=0;
int alongB=0;
for(i=0;alongA<n1&&alongB<n2;i++)
{
if(tempArrayA[alongA]<tempArrayB[alongB])
{
a[left+i]=tempArrayA[alongA];
alongA++;
}
else
{
a[left+i]=tempArrayB[alongB];
alongB++;
}
}
while(alongA<n1)
{
a[left+i]=tempArrayA[alongA];
i++;
alongA++;
}
while(alongB<n2)
{
a[left+i]=tempArrayB[alongB];
i++;
alongB++;
}
free(tempArrayA);
free(tempArrayB);
}
void MSort(int *a,int left,int right)
{
int center;
if(left<right)
{
center=(left+right)/2;
MSort(a,left,center);
MSort(a,center+1,right);
Merge(a,left,center+1,right);
}
}
void MergeSort(int *a,int n)
{
MSort(a,0,n-1);
}
void DisPlay(int a[],int n)
{
for(int i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
void main()
{
int array[LENGTH];
srand( (unsigned)time( NULL ) );
int TestNum=rand()%20+1;
for(int i=0;i<TestNum;i++)
{
cout<<"========第"<<i+1<<"组测试用例=========="<<endl;
for(int j=0;j<LENGTH;j++)
array[j]=rand()%100;
cout<<"排序前:";
for(int k=0;k<LENGTH;k++)
cout<<array[k]<<" ";
cout<<endl;
MergeSort(array,LENGTH);
cout<<"排序后:";
for(k=0;k<LENGTH;k++)
cout<<array[k]<<" ";
cout<<endl<<endl;
}
}
2)第二种写法:
#include<iostream.h>
#include<stdlib.h>
#include<time.h>
#define LENGTH 15
void Merge(int a[],int TempArray[],int Lpos,int Rpos,int RightEnd)
{
int i,LeftEnd,NumElements,TempPos;
LeftEnd=Rpos-1;
TempPos=Lpos;
NumElements=RightEnd-Lpos+1;
while(Lpos<=LeftEnd&&Rpos<=RightEnd)
if(a[Lpos]<=a[Rpos])
TempArray[TempPos++]=a[Lpos++];
else
TempArray[TempPos++]=a[Rpos++];
while(Lpos<=LeftEnd)
TempArray[TempPos++]=a[Lpos++];
while(Rpos<=RightEnd)
TempArray[TempPos++]=a[Rpos++];
for(i=0;i<NumElements;i++,RightEnd--)
a[RightEnd]=TempArray[RightEnd];
}
void MSort(int a[],int TempArray[],int left,int right)
{
int center;
if(left<right)
{
center=(left+right)/2;
MSort(a,TempArray,left,center);
MSort(a,TempArray,center+1,right);
Merge(a,TempArray,left,center+1,right);
}
}
void MergeSort(int a[],int n)
{
int *TempArray;
TempArray=(int*)malloc(n*sizeof(int));
if(TempArray!=NULL)
{
MSort(a,TempArray,0,n-1);
free(TempArray);
}
else
cout<<"No space for tmp array!!!";
}
void main()
{
int array[LENGTH];
srand( (unsigned)time( NULL ) );
int TestNum=rand()%20+1;
for(int i=0;i<TestNum;i++)
{
cout<<"========第"<<i+1<<"组测试用例=========="<<endl;
for(int j=0;j<LENGTH;j++)
array[j]=rand()%100;
cout<<"排序前:";
for(int k=0;k<LENGTH;k++)
cout<<array[k]<<" ";
cout<<endl;
MergeSort(array,LENGTH);
cout<<"排序后:";
for(k=0;k<LENGTH;k++)
cout<<array[k]<<" ";
cout<<endl<<endl;
}
}
浙公网安备 33010602011771号