/*
二路归并排序(递归实现)
*/
#include <iostream>
using namespace std;
int length=12;
int *data;
void Merge(int first1,int last1,int last2)
{
int *temp=new int[length];
int i=first1,j=last1+1,k=first1;
while (i<=last1&&j<=last2)
{
if(data[i]<=data[j])
temp[k++]=data[i++];
else
temp[k++]=data[j++];
}
while (i<=last1)
{
temp[k++]=data[i++];
}
while (j<=last2)
{
temp[k++]=data[j++];
}
for(i=first1;i<=last2;i++)
{
data[i]=temp[i];
}
delete[] temp;
}
void MergeSort(int first,int last)
{
if(first==last)return;
else
{
int mid=(first+last)/2;
MergeSort(first, mid);
MergeSort(mid+1, last);
Merge(first, mid, last);
}
}
int main()
{
data=new int[12]{8,3,2,6,7,1,5,4,9,13,12,10};
MergeSort(0, 11);
for(int i=0;i<12;i++)
{
cout<<data[i]<<"\t";
}
cout<<endl;
}
C++ 数据结构——二路归并排序(递归)
最新推荐文章于 2022-04-12 21:50:03 发布