#include <iostream>
#include <algorithm>
using namespace std;
template<class T>
void Merge(T *initList,T *mergedList, const int l, const int m, const int n) // l和m是下标,n是个数,
{
int i1,i2,iResult;
for(i1 = l, i2 = m + 1, iResult = l; i1 <= m && i2 <= n; iResult++)
{
if(initList[i1] <= initList[i2])
{
mergedList[iResult] = initList[i1];
i1++;
}
else
{
mergedList[iResult] = initList[i2];
i2++;
}
}
copy(initList + i1, initList + m +1, mergedList + iResult);
copy(initList + i2, initList + n +1, mergedList + iResult);
}
template<class T>
void MergePass(T *initList, T *resultList, const int n, const int s)
{
int i;
for(i = 1; i <= n -2*s+1; i+=2*s)
Merge(initList, resultList, i, i+s-1, i+2*s-1);
if((i+s-1)<n)
Merge(initList, resultList,i,i+s-1,n);
else
copy(initList+i,initList +n+1,resultList+i);
}
template<class T>
void MergeSort(T *a,const int n)
{
T *tempList = new int [n+1]; // tempList[0] 不用
for(int l=1;l<n;l*=2)
{
MergePass(a,tempList,n,l);
l*=2;
MergePass(tempList,a,n,l);
}
delete[] tempList;
}
int main()
{
int a[] = {0,3,5,8,9,2,4,6,7};
int b[9] = {0};
Merge(a,b,1,4,8);
for(int i =1;i<=8;i++)
cout << b[i] << " ";
cout << endl;
int m[] = {0,25,1,86,6,30,4,84};
int n[8] = {0};
MergePass(m,n,7,1);
for(int i = 1; i < 8; i++)
cout << n[i] << " ";
cout << endl;
MergePass(n,m,7,2);
for(int i = 1; i < 8; i++)
cout << m[i] << " ";
cout << endl;
MergePass(m,n,7,4);
for(int i = 1; i < 8; i++)
cout << n[i] << " ";
cout << endl;
cout << "上边的是中间结果的测试:" << endl;
cout << "下边的是MergeSort..." << endl;
int x[] = {0,25,1,86,6,30,4,84};
MergeSort(x,7);
for(int i=1;i<8;i++)
cout << x[i] << " ";
cout << endl;
return 0;
}
算法:归并排序
最新推荐文章于 2024-08-01 09:15:00 发布