#include <stdlib.h>
#include <assert.h>
//从 iM 将 iData[] 分为两个有序序列
template <typename T>
void Merge(T iData[], size_t iBegin, size_t iM, size_t iEnd)
{
T *iTmpData = new T[iEnd-iBegin+1];
assert(iTmpData);
size_t r = 0;
size_t iB1 = iBegin;
size_t iB2 = iM+1;
while (iB1<=iM && iB2<=iEnd)
iTmpData[r++] = iData[iB1]<=iData[iB2] ? iData[iB1++]:iData[iB2++];
while (iB1<=iM)
iTmpData[r++] = iData[iB1++];
while (iB2<=iEnd)
iTmpData[r++] = iData[iB2++];
r = 0;
printf(" mid:");
while (iBegin <= iEnd)
{
iData[iBegin/*++*/] = iTmpData[r++];
printf("%3.1d,", iData[iBegin++]);
}
printf("\n");
delete []iTmpData;
return;
}
template <typename T>
void MergeSort(T iData[], size_t iBegin, size_t iEnd)
{
size_t iMid = 0;
if (iBegin < iEnd)
{
iMid = (iBegin+iEnd)/2;
MergeSort(iData, iBegin, iMid);
MergeSort(iData, iMid+1, iEnd);
Merge(iData, iBegin, iMid, iEnd);
}
}
排序算法--归并排序
最新推荐文章于 2022-10-14 15:27:55 发布