【问题标题】:Merge sort using one array使用一个数组进行合并排序
【发布时间】:2014-10-24 14:25:12
【问题描述】:

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

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

我的归并排序算法是:

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

【问题讨论】:

标签: java mergesort array-algorithms


【解决方案1】:

检查这些链接:

How to sort in-place using the merge sort algorithm?

适合您问题的 Java 代码:

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

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

【讨论】:

    猜你喜欢
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2015-06-08
    相关资源
    最近更新 更多