TOPICS
Search

Heap


A binary heap in the minimum-heap convention is a sequence {a_n}_(n=1)^N satisfying a_(|_j/2_|)<=a_j for 2<=j<=N, where |_x_| is the floor function, which is equivalent to a_i<=a_(2i) for 1<=i<=|_N/2_| and a_i<=a_(2i+1) for 1<=i<=|_(N-1)/2_|. The first member must therefore be the smallest. A heap can be viewed as a labeled complete binary tree in which the label of each node is no greater than the labels of its descendants (Skiena 1990, p. 35). A heap with n elements supports arbitrary insertion and deletion of the minimum value in O(lnn) time per update (Skiena 1990, p. 38). Here, big-O notation O(g(n)) means that the running time is at most a fixed positive multiple of g(n) once n is sufficiently large.

Heaps

The minimum can be read in O(1) time. An algorithm due to Floyd (1964) builds a heap from a list of n elements in O(n) time, meaning that the running time grows at most linearly with the length of the list. For example, given the random permutation {6,2,7,9,5,3,4,8,10,1}, Floyd's algorithm gives the heap {1,2,3,8,5,7,4,9,10,6} (left figure). The right figure shows a heap containing 30 elements.

nheaps
1{1}
2{1, 2}
3{1, 2, 3}, {1, 3, 2}
4{1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 2, 4}

The numbers of heaps a(n) on n=1, 2, ... distinct ordered labels are 1, 1, 2, 3, 8, 20, 80, 210, 896, 3360, ... (OEIS A056971), the first few of which are summarized in the above table. A formula for a(n) is given by

 a(n)=(n-1; b+r_1)a(b+r_1)a(b+r_2)
(1)

for n>=2, with a(0)=a(1)=1, where h=|_log_2(n+1)_|-1, b=2^h-1, r=n-1-2b, r_1=r-|_r/2^h_|(r-2^h), and r_2=r-r_1.

The number of heaps with l fully occupied levels, or equivalently 2^l-1 elements, is given by the recurrence relation

 S_l=(2^l-2; 2^(l-1)-1)S_(l-1)^2
(2)

for integer l>=2, with S_1=1 (Skiena 1990, p. 36). This can be written as a product as

 S_l=((2^l-1)!)/(product_(k=1)^(l)(2^k-1)^(2^(l-k))),
(3)

the values of which for l=1, 2, ... are 1, 2, 80, 21964800, 74836825861835980800000, ... (OEIS A056972).


See also

Binary Tree, Complete Binary Tree, Heapsort, Priority Queue

Explore with Wolfram|Alpha

References

Floyd, R. W. "Algorithm 245: Treesort 3." Comm. ACM 7, 701, 1964. https://doi.org/10.1145/355588.365103.Knuth, D. E. The Art of Computer Programming, Vol. 3: Sorting and Searching, 2nd ed. Reading, MA: Addison-Wesley, 1998.Skiena, S. "Heaps." §1.4.4 in Implementing Discrete Mathematics: Combinatorics and Graph Theory with Mathematica. Reading, MA: Addison-Wesley, pp. 35-39, 1990.Skiena, S. S. "Heaps." §1.4.4 in The Algorithm Design Manual. New York: Springer-Verlag, pp. 35-39, 1997.Sloane, N. J. A. Sequences A056971 and A056972 in "The On-Line Encyclopedia of Integer Sequences."

Referenced on Wolfram|Alpha

Heap

Cite this as:

Weisstein, Eric W. "Heap." From MathWorld--A Wolfram Resource. https://mathworld.wolfram.com/Heap.html

Subject classifications