Heap (data structure)

The heap is one maximally efficient implementation of an abstract data type called a priority queue, and in fact, priority queues are often referred to as "heaps", regardless of how they may be implemented.

In a heap, the highest (or lowest) priority element is always stored at the root.

The maximum number of children each node can have depends on the type of heap.

Heaps are typically constructed in-place in the same array where the elements are stored, with their structure being implicit in the access pattern of the operations.

Heaps differ in this way from other data structures with similar or in some cases better theoretic bounds such as Radix trees in that they require no additional memory beyond that used for storing the keys.

Balancing a heap is done by sift-up or sift-down operations (swapping elements which are out of order).

Although different types of heaps implement the operations differently, the most common way is as follows: Construction of a binary (or d-ary) heap out of a given array of elements may be performed in linear time using the classic Floyd algorithm, with the worst-case number of comparisons equal to 2N − 2s2(N) − e2(N) (for a binary heap), where s2(N) is the sum of all digits of the binary representation of N and e2(N) is the exponent of 2 in the prime factorization of N.[7] This is faster than a sequence of consecutive insertions into an originally empty heap, which is log-linear.

Example of a binary max-heap with node keys being integers between 1 and 100
Example of a complete binary max-heap with node keys being integers from 1 to 100 and how it would be stored in an array.