c++ - 如何在不使用任何不必要空间的情况下合并三个排序数组?

标签 c++ arrays merge

例如,我编写了 C++ 代码来合并三个数组,但在这里您可以看到,我必须首先合并前两个数组,然后将其结果数组合并到第三个数组。

while (p < n1 && q < n2)    // n1,n2,n3 are sizes of a,b,c respectively 
{
    if (a[p] < b[q])    
    {
        res[r] = a[p];  // res is array is intermediate merged array
        r++;
        p++;
    }
    else
    {
        res[r] = b[q];
        r++;
        q++;
    }
}

while (q < n2)
{
    res[r] = b[q];
    r++;
    q++;
}

while (p < n1)
{
    res[r] = a[p];
    r++;
    p++;
}

while (s < r && t < n3)
{
    if (res[s] < c[t])
    {
        res2[r2] = res[s];  // res2 is finally merged array
        r2++;
        s++;
    }
    else
    {
        res2[r2] = c[t];
        r2++;
        t++;
    }
}

while (s < r)
{
    res2[r2] = res[s];
    s++;
    r2++;
}

while (t < n3)
{
    res2[r2] = c[t];
    r2++;
    t++;
}

我不想在我的程序中使用中间数组。有什么办法可以做到吗?

此外,是否有任何方法可以一次性合并任意数量的已排序数组?

最佳答案

我认为您正在研究就地合并排序,特别是最佳稳定合并。这不是一个微不足道的问题,已经在文献中进行了详细讨论。你可以开始阅读这个 here .

引自论文摘要:

This paper shows how to stably merge two sequences A and B of sizes m and n, m ≤ n, respectively, with O(m+n) assignments, O(mlog(n/m+1)) comparisons and using only a constant amount of additional space. This result matches all known lower bounds and closes an open problem posed by Dudzinski and Dydek in 1981. Our algorithm is based on the unstable algorithm of Mannila and Ukkonen. All techniques we use have appeared in the literature in more complicated forms but were never combined together. They are powerful enough to make stable all the existing linear in-place unstable algorithms we are aware of. We also present a stable algorithm that requires a linear number of comparisons and assignments which we consider to be the simplest algorithm for in-place merging.

关于c++ - 如何在不使用任何不必要空间的情况下合并三个排序数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31096097/

相关文章:

c++ - 这个线程池/多核模拟有什么问题

c++ - 我可以捆绑两个 MPI 消息吗?

Delphi:TImage.Create 导致访问冲突

javascript - 如何使用 javascript 正确迭代嵌套数组。

merge 期间的 Git pull 和 merge

c++ - 使用像 emwin QT 这样的 c/c++ 制作的具有自定义 GUI 的 Flash android 平板电脑

c++ - 如何在 C++ 中使用模板函数实现父类?

javascript - 最高得分词

merge - Keras 2.0 中的自定义合并层

python - 向左合并混合数量的标识符