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.
C DSA Implementation
basic.c
#include <stdio.h>
void print_list(int* values, int n) {
printf("[");
for (int i = 0; i < n; i++) { if (i) printf(", "); printf("%d", values[i]); }
printf("]");
}
void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; }
void heap_insert(int* heap, int* n, int value) {
heap[*n] = value; int child = *n; *n = *n + 1;
while (child > 0) {
int parent = (child - 1) / 2;
if (heap[parent] <= heap[child]) break;
swap(&heap[parent], &heap[child]);
child = parent;
}
}
int heap_pop(int* heap, int* n) {
int smallest = heap[0]; heap[0] = heap[*n - 1]; *n = *n - 1;
int parent = 0;
while (1) {
int left = parent * 2 + 1, right = left + 1;
if (left >= *n) break;
int child = left;
if (right < *n && heap[right] < heap[left]) child = right;
if (heap[parent] <= heap[child]) break;
swap(&heap[parent], &heap[child]);
parent = child;
}
return smallest;
}
int main(void) { int heap[16] = {2, 4, 7, 9, 6}; int n = 5; heap_insert(heap, &n, 1); print_list(heap, n); printf("\n"); }
@end @output [1, 4, 2, 9, 6, 7] @end