Write min_heap_insert With the Bubble-Up Loop Inside
Write min_heap_insert With the Bubble-Up Loop Inside
Write all of min_heap_insert, including the loop that carries the new value up the tree. There is no heapify_up helper in this file: the climb is yours to write.
Reminder: how this min heap is stored. A min_heap is a struct with three fields: capacity (the most values it can hold), count (how many it holds now) and values (a pointer to an array made with malloc). The heap is a complete binary tree kept in that array, filled row by row with no gaps, so only slots 0 to count - 1 are in use. Every parent is smaller than or equal to its children, so the smallest value is always at index 0. For the value at index i, the parent is at (i - 1) / 2 and the children are at 2 * i + 1 and 2 * i + 2.
The new value goes in the first free slot (index count). Then, while it is not at the root and it is smaller than its parent, swap the two and carry on from the parent's slot.
insert 1 (count is 5, so it starts at index 5):
i = 5, parent = 2 i = 2, parent = 0 i = 0: at the root, stop
1 < 6, swap 1 < 2, swap
2 2 1
/ \ / \ / \
4 6 4 1 4 2
/ \ / / \ / / \ /
8 5 1 8 5 6 8 5 6
2 4 6 8 5 1 2 4 1 8 5 6 1 4 2 8 5 6The loop has two reasons to stop: the value reached index 0, or its parent is not bigger. Check the index first, because index 0 has no parent to compare with.
Requirements:
1. When the heap is full, return false and change nothing.
2. Store the value at index count and add 1 to count.
3. While the value is not at index 0 and is smaller than its parent at (i - 1) / 2, swap them and move i to the parent.
4. Return true. Equal values do not swap.
Do NOT write a main function.
Expected Output:
insert 9: yes [9] insert 7: yes [7, 9] insert 5: yes [5, 9, 7] insert 3: yes [3, 5, 7, 9] insert 1: yes [1, 3, 7, 9, 5]
= newline. The output ends with a newline — print one after the last line.
Your Output
Run your code to see the output here...