08-heaps
Min-Heap Insert (Sift Up)
Insert one value into a min-heap and restore the parent-child order by sifting upward.
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.
Complexity
- Time: O(log n)
- Space: O(1) extra
sift up
A new value starts at the end of the array and swaps with its parent while it is smaller.
Visual walkthrough
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(2, 4, 7, 9, 6)
heap <- heap_insert(heap, 1)
cat(list_string(heap), "\n", sep = "")
Implementation notes
heap <- c(2, 4, 7, 9, 6)is the starting min-heap vector. This lesson uses R's 1-based indexes.- The output path calls
heap <- heap_insert(heap, 1).heap_pop()is present in the shared file, but it is not used for this lesson's printed result. heap_insert()appends withheap <- c(heap, value), producing[2, 4, 7, 9, 6, 1], then startschild <- length(heap)at index6.parent <- floor(child / 2)follows the 1-based heap relationship: child6has parent3, then child3has parent1.if (heap[parent] <= heap[child]) breakstops when min-heap order is already valid. Otherwise thetmpline swaps the parent and child values.
Replay steps
start: [2, 4, 7, 9, 6]
append 1: [2, 4, 7, 9, 6, 1]
swap 1/7: [2, 4, 1, 9, 6, 7]
swap 1/2: [1, 4, 2, 9, 6, 7]
list_string(heap)formats[1, 4, 2, 9, 6, 7], andcat(..., "\n", sep = "")prints that exact line.
Output
[1, 4, 2, 9, 6, 7]