data-structures algorithms

Definition

Heap

A heap is a specialised tree-based data structure that satisfies the heap property:

  • Max-Heap Property: For every node other than the root, the value of is at most the value of its parent:. Thus, the largest element in a max-heap is stored at the root.
  • Min-Heap Property: For every node other than the root, the value of is at least the value of its parent:. Thus, the smallest element in a min-heap is stored at the root.

A heap is typically implemented as a complete binary tree, meaning all levels are fully filled except possibly the lowest, which is filled from left to right.

Implementation

Heaps are most efficiently implemented using an array. For a node at index (using 0-based indexing), its relative positions are determined as follows:

The following diagram illustrates a max-heap and its corresponding representation in an array:

Complexity

The following table outlines the time complexity of common heap operations for a heap containing elements:

OperationComplexityDescription
Access the root element of the heap.
Add an element at the end and “bubble up” to maintain the heap property.
Replace the root with the last element and “bubble down”.
Convert an unordered array into a heap using a bottom-up approach.
Restore the heap property at a specific node.