I am trying to prove that for binary heaps, buildHeap does at most (2N-2) comparisons between elements. I find it very difficult to prove this claim.
相关问题
- Finding k smallest elements in a min heap - worst-
- binary search tree path list
- High cost encryption but less cost decryption
- How to get a fixed number of evenly spaced points
- Space complexity of validation of a binary search
相关文章
- What is the complexity of bisect algorithm?
- What are the problems associated to Best First Sea
- Coin change DP solution to keep track of coins
- Algorithm for partially filling a polygonal mesh
- Robust polygon normal calculation
- Algorithm for maximizing coverage of rectangular a
- How to measure complexity of a string?
- Select unique/deduplication in SSE/AVX
The build-heap algorithm starts at the midpoint and moves items down as required. Let's consider a heap of 127 items (7 levels). In the worst case:
So in the worst case you have
So in the worst case, build-heap makes fewer than N swaps.
Because build-heap requires that you swap an item with the smallest of its children, it requires two comparisons to initiate a swap: one to find the smallest of the two children, and one to determine if the node is larger and must be swapped.
The number of comparisons required to move a node is
2*(levels_moved+1)
, and no more than N/2 nodes will be moved.The general case
We need to prove that the maximum number of comparisons is no more than 2N-2. As I noted above, it takes two comparisons to move a node one level. So if the number of levels moved is less than N (i.e. (N-1) or fewer), then the maximum number of comparisons cannot exceed 2N-2.
I use a full heap in the discussion below because it represents the worst case.
In a full heap of N items, there are (N+1)/2 nodes at the leaf level. (N+1)/4 at the next level up. (N+1)/8 at the next, etc. You end up with this:
That gives us the series:
Let's see what that does for heaps of different sizes:
I ran that for heaps up of up to 20 levels (size a million and change), and it holds true: the maximum number of levels moved for a full heap of N items is N-log2(N+1).
Taking the above series as an Arithetico-geometric Sequence, we compute the sum for
log2(N + 1) - 1
terms, ignoring the first term as it is zero, to be equal toN - 1
. (Recall that a full binary tree haslog2(N + 1)
levels)This sum represents the total number of times a siftup operation was performed. The total number of comparisons thus required is
2N - 2
(since each sift up operation requires two comparisons). This is also the upper bound, since a full binary tree always represents the worst case for a given tree depth.