Definition
Max-Heap
A max-heap is a heap that satisfies the max-heap property: for every node other than the root, the value of the parent is at least the value of the node itself:
Consequently, the largest element in a max-heap is always stored at the root, and the values in any path from the root to a leaf are in non-increasing order.
Operations
Max-Heapify
The procedure is essential for maintaining the max-heap property. Given an array and an index , it assumes that the binary trees rooted at and are already max-heaps, but that might be smaller than its children.
Extract Max
To extract the maximum element:
- Copy the root value (the maximum).
- Replace the root with the last element in the array.
- Decrease the heap size.
- Call on the root to restore the heap property.
Insert
To insert a new element :
- Add at the end of the heap (the next available leaf position).
- “Bubble up” (or ): compare with its parent and swap if is larger, repeating until the max-heap property is satisfied.
Complexity
The time complexity for max-heap operations depends on the height of the tree:
- Max-Heapify:
- Insert:
- Extract-Max:
- Build-Max-Heap: