【问题标题】:K way merge of sorted arrays implementation using a min heap使用最小堆实现排序数组的 K 路合并
【发布时间】:2015-04-05 06:42:26
【问题描述】:

我一直在试图弄清楚如何为 K 路合并实现以下算法。

Algorithm:
1)Initialize an array of size n*k. 
2) Initialize a min heap of size k, to hold the smallest element of each array.
3) Add the smallest element from the minHeap into the output array.
4)Move the next element from the array from which the min element was derived onto the heap. // How would one implement this?
5) Repeat step 4 until all the arrays are empty and the minHeap is empty.

除了算法的第 4 步之外,我已经能够实现所有其他操作。如何跟踪从中提取了最小元素的数组?

【问题讨论】:

    标签: arrays algorithm merge


    【解决方案1】:

    尝试在pair 中保留元素和数组。元素是键,数组(指向它的指针)是值。对应该可以按它的键排序。
    当您从堆中提取最小的对时,您将从对中获取键作为您想要的元素,并且该对中的值将是包含该元素的数组。

    重要提示:根据您使用的语言,不要将数组复制为值,而只保存指向它们的指针(比如说在 C++ 中)或它们的引用(即 Java)。

    【讨论】:

      猜你喜欢
      • 2013-04-10
      • 1970-01-01
      • 2018-04-12
      • 2020-02-23
      • 2021-11-27
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多