简体   繁体   English

无法理解K路合并算法(给出了计数器示例)

[英]Having trouble understanding the K-way merge algorithm (Counter example given)

In K way merge sort, the solution that uses a heap: essentially maintains a heap and constantly extracts max from that heap. 在K方式合并排序中,使用堆的解决方案:本质上是维护堆并不断从该堆中提取max。 I have a counterexample for why this won't work well. 我有一个反例,说明为什么这不能很好地工作。

5 -> 1 -> 0
4 -> 2 -> 1
3 -> 2 -> 0

Suppose we initialize our heap. 假设我们初始化堆。 It contains {5, 4, 3}. 它包含{5,4,3}。

We run extract max, we obtain 5 and add that into our new list (that represents the final solution). 我们运行extract max,获得5并将其添加到新列表中(代表最终解决方案)。 Our heap now looks like {4,3}. 现在,我们的堆看起来像{4,3}。 We then refill our heap with the head of list that we extracted the max element from. 然后,我们从提取max元素的列表的开头重新填充堆。

This implies that we get something like this: {4, 3, 1}. 这意味着我们得到了这样的信息:{4,3,1}。

This doesn't make sense to me. 这对我来说没有意义。 This heap doesn't represent the top K elements anymore. 该堆不再代表前K个元素。 1 shouldn't be used to refill the heap, it should have been 2. So, this O(nlgk) method doesn't make much sense to me. 1不应该用来填充堆,应该是2。所以,这种O(nlgk)方法对我来说没有多大意义。

I hope someone can shed light on how this algorithm works because I'm stuck here. 我希望有人可以阐明该算法的工作原理,因为我一直在这里。

The max heap always contains the max elements of k lists (or arrays). 最大堆始终包含k个列表(或数组)的最大元素。 For your 'counter' example: 对于您的“计数器”示例:

5 -> 1 -> 0
4 -> 2 -> 1
3 -> 2 -> 0

The heap is {5, 4, 3} contains max elements of these three lists. 堆{5,4,3}包含这三个列表的最大元素。

Now you extract 5 from the heap, means you also remove 5 from the first list: 现在,您从堆中提取5,这意味着您还从第一个列表中删除了5:

5-->1-->0: after extract 5, the list now is 1-->0: so 1 now is the top of the list.

Then the new heap is {4, 3, 1}, still contains max elements of lists. 然后,新堆为{4,3,1},仍然包含列表的最大元素。

Lets continue your example: the current heap after extracting 5 and heapifying is: 让我们继续您的示例:提取5并进行堆化后的当前堆为:

{4, 3, 1}

Extract 4 from the heap, means you also remove 4 from: 从堆中提取4,这意味着您还要从以下内容中删除4:

4-->2-->1: remove 4 you have 2-->1. 2 now is the top element of the list.

Then a new heap now is 然后是一个新的堆

{3, 2, 1}

Keep doing this, you get what you want (descending list). 继续这样做,您将得到想要的(降序列表)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM