08-heaps
Min-Heap Pop (Sift Down)
Remove the minimum value, move the last item to the root, and sift downward.
Algorithm
@steps
- Store the heap in an array.
- Compare parent and child indexes instead of building explicit tree nodes.
- Swap only when the heap order is violated.
- Print the deterministic final heap state for replay comparison. @end @complexity
- Time: O(log n)
- Space: O(1) extra @end
sift down
After removing the root, the last value moves to the root and swaps with the smaller child until order is restored.
R DSA Implementation
basic.R
list_string <- function(values) paste0("[", paste(values, collapse = ", "), "]")
heap_insert <- function(heap, value) {
heap <- c(heap, value)
child <- length(heap)
while (child > 1) {
parent <- floor(child / 2)
if (heap[parent] <= heap[child]) break
tmp <- heap[parent]; heap[parent] <- heap[child]; heap[child] <- tmp
child <- parent
}
heap
}
heap_pop <- function(heap) {
smallest <- heap[1]
heap[1] <- heap[length(heap)]
heap <- heap[-length(heap)]
parent <- 1
while (TRUE) {
left <- parent * 2
right <- left + 1
if (left > length(heap)) break
child <- left
if (right <= length(heap) && heap[right] < heap[left]) child <- right
if (heap[parent] <= heap[child]) break
tmp <- heap[parent]; heap[parent] <- heap[child]; heap[child] <- tmp
parent <- child
}
list(value = smallest, heap = heap)
}
heap <- c(1, 4, 2, 9, 6, 7)
result <- heap_pop(heap)
cat(result$value, " -> ", list_string(result$heap), "\n", sep = "")
@end @output 1 -> [2, 4, 7, 9, 6] @end