我的合并排序算法如下...
我们知道这个算法需要额外的内存。有没有办法只用一个数组进行排序?(在单个数组中排序。)
我的合并排序算法是:
//LeftPos = start of left half;
//RightPos = start of right half
void Merge(int A[ ], int LeftPos, int RightPos, int RightEnd)
{
int LeftEnd = RightPos – 1;
int TmpPos = 1
int NumElements = RightEnd – LeftPos + 1;
int TempArray[NumElements];
while(leftPos <= LeftEnd && RightPos <= RightEnd)
if(A[LeftPos] <= A[RightPos])
TmpArray[TmpPos++] = A[LeftPos++];
else
TmpArray[TmpPos++] = A[RightPos++];
while(LeftPos <= LeftEnd) //Copy rest of first half
TmpArray[TmpPos++] = A[LeftPos++];
while(RightPos <= RightEnd) //Copy rest of second half TmpArray[TmpPos++] = A[RightPos++];
for(int i = 1; i <= NumElements; i++) //Copy TmpArray back
A[LeftPos++] = TmpArray[i];
}