Insert one value into a min-heap and restore the parent-child order by sifting upward.

Algorithm

@steps

  1. Store the heap in an array.
  2. Compare parent and child indexes instead of building explicit tree nodes.
  3. Swap only when the heap order is violated.
  4. Print the deterministic final heap state for replay comparison. @end @complexity
  • Time: O(log n)
  • Space: O(1) extra @end
sift up A new value starts at the end of the array and swaps with its parent while it is smaller.

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 = "")

@end @output [1, 4, 2, 9, 6, 7] @end