0

我的合并排序算法如下...

我们知道这个算法需要额外的内存。有没有办法只用一个数组进行排序?(在单个数组中排序。)

我的合并排序算法是:

//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];
}
4

1 回答 1

0

检查这些链接:

如何使用归并排序算法就地排序?

适合您问题的Java代码:

https://github.com/bakeraj4/In-Place-Merge-Sort/blob/master/mergeMain.java

您正在寻找的技术是“就地”,对于将来的搜索,您可以使用它在互联网上找到更好的结果。

于 2014-10-24T14:37:03.477 回答