What is the Heap Technique?
The Heap Technique is a method of organizing elements in a binary tree structure where the parent node always maintains a relationship with its children based on either:
- Max Heap: Parent ≥ Children
- Min Heap: Parent ≤ Children
Heaps are typically implemented as arrays and are ideal for scenarios requiring repeated access to the largest or smallest element.
Common Heap Operations
- Insert: Add a new element while maintaining the heap property.
- Delete: Remove the top element (max or min), then re-heapify.
- Heapify: Convert an array into a valid heap.
Pseudocode: Inserting into a Heap
// Insert value into heap and bubble it up
function insert(heap, value):
heap.append(value)
index = heap.length - 1
while index > 0:
parent = floor((index - 1) / 2)
if heap[parent] < heap[index]: // Max Heap
swap(heap[parent], heap[index])
index = parent
else:
break
Pseudocode: Heapify an Array
// Heapify subtree rooted at index 'i' for Max Heap
function heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[left] > arr[largest]:
largest = left
if right < n and arr[right] > arr[largest]:
largest = right
if largest != i:
swap(arr[i], arr[largest])
heapify(arr, n, largest)
Pseudocode: Build Max Heap from Unordered Array
function buildMaxHeap(arr):
n = arr.length
for i from floor(n/2) - 1 down to 0:
heapify(arr, n, i)