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. @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.
Fortran DSA Implementation
basic.f90
program main
implicit none
integer :: heap(16), n, popped, top(16)
heap = 0; heap(1:5) = [2, 4, 7, 9, 6]; n = 5
call heap_insert(heap, n, 1)
call print_list(heap, n)
contains
subroutine print_list(values, count)
integer, intent(in) :: values(16), count
integer :: i
write(*, '(A)', advance='no') '['
do i = 1, count
if (i > 1) write(*, '(A)', advance='no') ', '
write(*, '(I0)', advance='no') values(i)
end do
print '(A)', ']'
end subroutine print_list
subroutine swap(a, b)
integer, intent(inout) :: a, b
integer :: tmp
tmp = a; a = b; b = tmp
end subroutine swap
subroutine heap_insert(heap, n, value)
integer, intent(inout) :: heap(16), n
integer, intent(in) :: value
integer :: child, parent
n = n + 1; heap(n) = value; child = n
do while (child > 1)
parent = child / 2
if (heap(parent) <= heap(child)) exit
call swap(heap(parent), heap(child))
child = parent
end do
end subroutine heap_insert
subroutine heap_pop(heap, n, popped)
integer, intent(inout) :: heap(16), n
integer, intent(out) :: popped
integer :: parent, left, right, child
popped = heap(1); heap(1) = heap(n); n = n - 1; parent = 1
do
left = parent * 2; right = left + 1
if (left > n) exit
child = left
if (right <= n .and. heap(right) < heap(left)) child = right
if (heap(parent) <= heap(child)) exit
call swap(heap(parent), heap(child))
parent = child
end do
end subroutine heap_pop
subroutine keep_top(heap, n, value, k)
integer, intent(inout) :: heap(16), n
integer, intent(in) :: value, k
integer :: removed
call heap_insert(heap, n, value)
if (n > k) call heap_pop(heap, n, removed)
end subroutine keep_top
end program main
@end @output [1, 4, 2, 9, 6, 7] @end