CJCoding With Joseph
15free / daySign inCreate account

Insert Into a Max Heap

Complete insert(int value) so it adds a value to the max 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 max heap is. A max heap is the mirror image of a min heap: a complete binary tree stored in an array with no gaps, where every parent is greater than or equal to its children. That puts the largest value at index 0, which makes a max heap the natural shape for anything where the biggest priority goes first, like a leaderboard. The index math does not change: the parent of index i is at (i - 1) / 2. A heap is still not a BST, so the two children of a node can be in either order.

start:              9 4 7
put 12 at the end:  9 4 7 12    (index 3, parent index 1 holds 4)
12 > 4, swap:       9 12 7 4    (now index 1, parent index 0 holds 9)
12 > 9, swap:       12 9 7 4    (now index 0, the root: stop)

Sifting up works exactly as it does in a min heap with the comparison flipped: the new value starts in the first free slot and keeps swapping with its parent while it is larger than that parent.

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 as soon as the parent is greater than or equal to the value, so equal values never swap. 4. Return true once the value is in place.

Do NOT write a main method.

Expected Output:

MaxHeap: 3
MaxHeap: 8 3
MaxHeap: 8 3 5
MaxHeap: 10 8 5 3
MaxHeap: 10 8 5 3 2
10 5

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

Hints4 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 (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.