#include "stdafx.h"
//Lpos前半部分起始位置,Rpos后半部分起始位置,RightEnd结束位置
void Merge(int A[], int TmpArray[], int Lpos, int Rpos, int RightEnd)
{
int startIndex = Lpos;
int endIndex = RightEnd;
int tmpIndex = Lpos;
while ((Lpos <= Rpos - 1) && (Rpos <= RightEnd)) //若前后都未出界
{
if (A[Lpos] < A[Rpos]) //左边的小,记左边的
TmpArray[tmpIndex++] = A[Lpos++];
else //右边的小,记右边的
TmpArray[tmpIndex++] = A[Rpos++];
}
while (Lpos < Rpos) //左边还有剩(已排序),全填入TmpArray
TmpArray[tmpIndex++] = A[Lpos++];
while (Rpos <= RightEnd) //右边还有剩(已排序),全填入TmpArray
TmpArray[tmpIndex++] = A[Rpos++];
while (startIndex <= endIndex) //把TmpArray中的排序结果填入A中
{
A[startIndex] = TmpArray[startIndex];
startIndex++;
}
}
void MergeSort(int A[], int TmpArray[], int Left, int Right)
{
int center = 0;
if (Left < Right)
{
center = (Left + Right) / 2;
MergeSort(A,TmpArray,Left,center);
MergeSort(A,TmpArray,center+1,Right);
Merge(A,TmpArray,Left,center+1,Right);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int A[] = {3,5,9,7,1,4,2,0,8,6};
int B[10] = {};//需要一个外部数组
MergeSort(A,B,0,9);
return 0;
}