CJCoding With Joseph
15free / daySign inCreate account

Peek at the Smallest Value

Complete heap_peek(const MinHeap *heap, int *out). It copies the smallest value into *out and returns 1, or returns 0 when the heap is empty.

Reminder: the smallest value is always at the root. A min heap is a complete binary tree kept in an array, and every parent is smaller than or equal to its children. Follow any path down from the root and the values never get smaller, so the root, index 0, holds the smallest value in the whole heap. Peeking means looking at that value without taking it out.

a heap with 6 values
index:   0   1   2   3   4   5
value:   5   9   6  12  10   8
         ^
         heap_peek copies this 5 into *out and returns 1

            5               <- index 0, the smallest
          /   \
         9     6
        / \   /
      12  10 8

after the peek: the same six values in the same six slots

an empty heap (size 0): no slots in use
         heap_peek returns 0 and does not touch *out

what the caller sees
    int smallest = -1;
    heap_peek(&heap, &smallest);    the heap above: returns 1, smallest is now 5

    int other = -1;
    heap_peek(&empty, &other);      an empty heap: returns 0, other is still -1

The function hands back two things at once: the return value says whether there was anything to see, and *out carries the value itself. That way a heap whose smallest value is 0 is never confused with an empty heap.

Requirements: 1. When the heap has at least one value, store heap->data[0] in *out and return 1. 2. When the heap is empty, return 0 and leave *out exactly as the caller set it. 3. Peeking does not change the heap: no value moves and size stays the same, which is why the heap is const. 4. Use the provided heap_is_empty for the empty check, and leave the other functions as they are.

Do NOT write a main function.

Expected Output:

MinHeap: 4 7 9 8 10 12
peek: 4
peek: 4
MinHeap: 4 7 9 8 10 12

= newline. The output ends with a newline — print one after the last line.

Hints3 available
Topics:
Data Structures & AlgorithmsHeaps
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (p, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.