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
Java DSA Implementation
Basic.java
import java.util.*;
class Basic {
static String listString(List<Integer> values) { return values.toString(); }
static void heapInsert(List<Integer> heap, int value) {
heap.add(value);
int child = heap.size() - 1;
while (child > 0) {
int parent = (child - 1) / 2;
if (heap.get(parent) <= heap.get(child)) break;
Collections.swap(heap, parent, child);
child = parent;
}
}
static int heapPop(List<Integer> heap) {
int smallest = heap.get(0);
heap.set(0, heap.remove(heap.size() - 1));
int parent = 0;
while (true) {
int left = parent * 2 + 1;
int right = left + 1;
if (left >= heap.size()) break;
int child = left;
if (right < heap.size() && heap.get(right) < heap.get(left)) child = right;
if (heap.get(parent) <= heap.get(child)) break;
Collections.swap(heap, parent, child);
parent = child;
}
return smallest;
}
public static void main(String[] args) { List<Integer> heap = new ArrayList<>(Arrays.asList(2, 4, 7, 9, 6)); heapInsert(heap, 1); System.out.println(listString(heap)); }
}
Output
[1, 4, 2, 9, 6, 7]
Implementation notes
- Java stores the heap as a
List<Integer>backed by anArrayList, seeded withnew ArrayList<>(Arrays.asList(2, 4, 7, 9, 6)). Heap entries are boxed throughInteger.valueOf, so these small fixture values may be cachedIntegerinstances rather than primitiveintarray slots. heapInsertmutates the same list withheap.add(value), then starts the new child atheap.size() - 1and computes each parent as(child - 1) / 2.- This is a min-heap: the sift-up loop stops when
child == 0orheap.get(parent) <= heap.get(child), which unboxes the twoIntegervalues for primitive comparison. OtherwiseCollections.swap(heap, parent, child)exchanges the two list positions and continues from the parent index. - The replay-visible states show append
[2, 4, 7, 9, 6, 1], then swaps to[2, 4, 1, 9, 6, 7]and[1, 4, 2, 9, 6, 7]. Allocation is theArrayListstorage and any uncached boxed integers, all managed by JVM GC.