#include <iostream>
using namespace std;
//取左孩子节点坐标
#define GetLeftChild(x) (2*(x)+1)
//取右孩子节点坐标 这里可能不需要
#define GetRightChild(x) (2*(x)+2)
void Show(int* pList, int nCount)
{
for (int nIndex = 0; nIndex < nCount; nIndex++)
cout << pList[nIndex] << "\t";
cout << endl;
}
/*
将两个有序表合并成一个有序表
*/
void Merge(int* pList,int nBegin_1,int nEnd_1,int* pTemp,int nBegin_2,int nEnd_2)
{
int nIndex = nBegin_1;
int nLen = nBegin_1;
while ((nBegin_1 <= nEnd_1) && (nBegin_2 <= nEnd_2))
{
if (pList[nBegin_1] <= pList[nBegin_2])
pTemp[nIndex++] = pList[nBegin_1++];
else
pTemp[nIndex++] = pList[nBegin_2++];
}
//如果还有剩余数据,就直接移动到辅助
while (nBegin_1 <= nEnd_1)
pTemp[nIndex++] = pList[nBegin_1++];
while (nBegin_2 <= nEnd_2)
pTemp[nIndex++] = pList[nBegin_2++];
nIndex--;
while (nIndex >= nLen)
{
pList[nIndex] = pTemp[nIndex];
nIndex--;
}
}
/*
归并排序
*/
void MergeSort(int* pList,int nBegin,int nEnd,int* pTemp)
{
if (nBegin < nEnd)
{
int nIndex = (nBegin + nEnd) / 2;//分组的中点
MergeSort(pList, nBegin, nIndex, pTemp);//对左边进行归并排序
MergeSort(pList, nIndex + 1, nEnd, pTemp);//对右边进行归并排序
Merge(pList, nBegin, nIndex, pTemp, nIndex + 1, nEnd);//合并两端
}
}
int main(int argc, char* argv[], char* enp[])
{
int pList[] = {15,78,95,65,35,12,47,55,22,77};
int nCount = sizeof(pList) / sizeof(int);
shared_ptr<int> pShareTemp(new int[nCount]);
int* pTemp = pShareTemp.get();
MergeSort(pList, 0, nCount-1, pTemp);
Show(pList, nCount);
system("pause");
return 0;
}