data-structures algorithms

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:

  1. Copy the root value (the maximum).
  2. Replace the root with the last element in the array.
  3. Decrease the heap size.
  4. Call on the root to restore the heap property.

Insert

To insert a new element :

  1. Add at the end of the heap (the next available leaf position).
  2. “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: