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
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"); }
Output
[1, 4, 2, 9, 6, 7]
Implementation notes
- C stores the heap in stack array
int heap[16] = {2, 4, 7, 9, 6}with scalar sizeint n = 5; the capacity is fixed by the array declaration, and this source does not add a bounds check before insertion. heap_insert(int* heap, int* n, int value)receives the array as a pointer and the size by pointer, soheap[*n] = valueand*n = *n + 1mutate caller state.- Sift-up uses signed
intindexes:childstarts at the inserted slot andparent = (child - 1) / 2; the loop stops at the root or whenheap[parent] <= heap[child]. swap(int* a, int* b)exchanges two heap slots through pointers using stack temporaryint t; no second heap array is allocated.- The trace records
[2, 4, 7, 9, 6], append to[2, 4, 7, 9, 6, 1], swap with parent7to[2, 4, 1, 9, 6, 7], then swap with parent2to[1, 4, 2, 9, 6, 7]. print_list(int* values, int n)receives the heap as a pointer after array decay and prints comma-separated integers withprintf, followed by a newline inmain.