Peek at the Root Through an Out Parameter
Peek at the Root Through an Out Parameter
Complete min_heap_peek. It reports the smallest value in the heap without removing it.
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.
This function has two things to say: whether there was a value at all, and what it was. A C function returns only one thing, so the lab uses a common pattern: the bool return says whether it worked, and the value travels back through the pointer parameter value (an "out parameter").
3 the caller writes:
/ \
8 5 int smallest;
/ bool ok = min_heap_peek(heap, &smallest);
9
after the call:
values: 3 8 5 9 ok is true
index: 0 1 2 3 smallest is 3 (written through the pointer)
the heap still holds 4 valuesWhen the heap is empty there is no root to report. Return false and do not write anything through the pointer.
Requirements:
1. When the heap is empty, return false and leave *value alone.
2. Otherwise copy the value at index 0 into *value and return true.
3. Do not change the heap.
Do NOT write a main function.
Expected Output:
peeked: yes, value 2 count is still 4 peeked again: yes, value 2
= newline. The output ends with a newline — print one after the last line.
Your Output
Run your code to see the output here...