本文介绍了如何实现C ++中的make_heap具有3N的复杂性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在C ++中make_heap的算法是什么,复杂性是3 * N?只有我能想到的通过插入元素有一个复杂的O(N Log N)做一个堆。非常感谢!

I wonder what's the algorithm of make_heap in in C++ such that the complexity is 3*N? Only way I can think of to make a heap by inserting elements have complexity of O(N Log N). Thanks a lot!

推荐答案

将堆表示为数组。 i '下面的两个元素位于 2 * i + 1 2 * i + 2 。如果数组有 n 个元素,那么从结尾开始,取每个元素,让它落到堆中的正确位置。这是 O(n)运行。

You represent the heap as an array. The two elements below the i'th element are at positions 2*i+1 and 2*i+2. If the array has n elements then, starting from the end, take each element, and let it "fall" to the right place in the heap. This is O(n) to run.

为什么?好的 n / 2 的元素没有孩子。 n / 4 有一个高度为1的子树。对于 n / 8 ,有一个高度为2的子树。对于 n / 16 高度为3的子树。所以我们得到 n / 2 + 2 * n / 2 + 3 * n / 2 + 2*n/2 + 3*n/2 + ... = (n/2)(1 * (1/2 + 1/4 + 1/8 + . ...) + (1/2) * (1/2 + 1/4 + 1/8 + . ...) + (1/4) * (1/2 + 1/4 + 1/8 + . ...) + ...) = (n/2) * (1 * 1 + (1/2) * 1 + (1/4) * 1 + ...) = (n/2) * 2 = n. So the total number of "see if I need to fall one more, and if so which way do I fall? comparisons comes to n. But you get round-off from discretization, so you always come out to less than n sets of swaps to figure out. Each of which requires at most 3 comparisons. (Compare root to each child to see if it needs to fall, then the children to each other if the root was larger than both children.)

这篇关于如何实现C ++中的make_heap具有3N的复杂性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 18:34