Pointer Dereferencing Levels
Understanding the four levels of pointer indirection in heap implementation
Level 1: ELEMENT
(*v)[i]->index
What it represents: One struct (index, key, pos)
Explanation: Direct access to struct fields
struct ELEMENT {
int index;
double key;
int pos;
};
Level 2: ELEMENT*
(*v)[i]
What it represents: Pointer to one struct
Explanation: Pointer to a single ELEMENT struct
Level 3: ELEMENT**
*v
What it represents: Array of pointers to structs
Explanation: Array where each element points to an ELEMENT struct
Level 4: ELEMENT***
v
What it represents: Pointer to the array itself
Explanation: Pointer to the array of pointers
Key Implementation Relationships
Min Heapify
Corrects a single violation of the min-heap property by moving an element down the tree.
Detailed Pseudocode
MinHeapify(heap, v, i):
# push the element at i down until the min-heap property holds
while i has at least one child:
j = index of the smaller child of i
if key(i) <= key(j):
break
swap i and j in the heap (also update v[*].pos)
i = j
Implementation Details
Build Heap
Converts an arbitrary array into a min-heap by calling min-heapify from last non-leaf to root.
Detailed Pseudocode
BuildHeap(heap, v):
# turn an arbitrary array into a min-heap
set heap contents to elements 1..n and record their positions
for i from floor(n/2) down to 1:
MinHeapify(heap, v, i)
Implementation Details
Insert
Adds a new element to the heap and maintains the min-heap property by moving it up the tree.
Detailed Pseudocode
Insert(heap, v, element_index):
# add one element and restore heap order by bubbling up
append element_index at the end of the heap; set its position
i = current position of element_index
while i has a parent and key(parent(i)) > key(i):
swap i with parent(i) (also update positions)
i = parent(i)
Implementation Details
Decrease Key
Decreases the value of a key at a given position and maintains min-heap property by moving it up.
Detailed Pseudocode
DecreaseKey(heap, v, element_index, new_key):
# lower an element's key, then bubble up like Insert
set key(element_index) = new_key
i = current position of element_index
while i has a parent and key(parent(i)) > key(i):
swap i with parent(i) (also update positions)
i = parent(i)
Implementation Details
Extract Min
Removes and returns the minimum element (root) and restructures the heap to maintain min-heap property.
Detailed Pseudocode
ExtractMin(heap, v):
# remove and return the minimum (root) and restore the heap
if heap is empty:
return null
min_idx = root element's index
move last element to root and update its position
reduce heap size by one
MinHeapify(heap, v, 1)
return min_idx