Insert Into a Min Heap (Sift Up)
Insert Into a Min Heap (Sift Up)
Complete insert(int value) so it adds a value to the min heap and keeps the heap rule true. It returns true when the value was stored and false when the heap is full.
Reminder: what a min heap is. A min heap is a complete binary tree stored in an array, filled left to right with no gaps. Every parent is smaller than or equal to its children, so the smallest value always sits at index 0. For the node at index i, the parent is at (i - 1) / 2, the left child at 2 * i + 1 and the right child at 2 * i + 2. A heap is not a BST: it only cares about parent and child, never about left versus right.
start: 3 8 6
put 2 at the end: 3 8 6 2 (index 3, parent index 1 holds 8)
2 < 8, swap: 3 2 6 8 (now index 1, parent index 0 holds 3)
2 < 3, swap: 2 3 6 8 (now index 0, the root: stop)Adding a value is called sifting up (or bubbling up): the new value goes in the first free slot at the end of the array, then it keeps swapping with its parent while it is smaller than that parent. It stops when the parent is smaller or equal, or when it reaches the root.
Requirements:
1. Return false and change nothing when size already equals the array length.
2. Store value at index size, then increase size by one.
3. Sift it up with the provided parent(int i) and swap(int i, int j) helpers. Stop at index 0, or when the parent is not bigger than the value, so equal values never swap.
4. Return true once the value is in place.
Do NOT write a main method.
Expected Output:
MinHeap: 10 MinHeap: 4 10 MinHeap: 4 10 7 MinHeap: 1 4 7 10 MinHeap: 1 4 7 10 6 1 5
= newline. The output ends with a newline — print one after the last line.
Your Output
Run your code to see the output here...