- There are two types of heap and one of that is Max heap.
- In Max heap, we have to add element such that parent has maximum value than it’s child value.
- Here we represent Max heap as binary tree and we are going to implement it with static array in which zero index has no value. We add value in array starting from index one as show in figure.
- Here we have same concept of queue that FIFO(first in – first out)
Functionality :-
- Enqueue – Add element at last.
- Dequeue – Delete from first position.
- Peek – Display First Element
Advantage of Max heap :- Sorting become more efficient.
Enqueue :-
- Suppose if we want to add 25 in upper Max heap than we have to add 25 at index 11 (suppose index 11 is there.).But as we know Max heap means child has minimum value that it’s parent but here 7<25, which is not possible that we have to swap that two value for that what can do that Number[i/2]<->Number[i] means as we can here we have index 11 if take 11/2=5(in integer) than you can directly jump at it’s parent value and exchange that value.After exchanging that two value you will again find that 14<25 that again you can change that value with upper logic like this we have to move till we don’t find that Number[i/2]>Number[i].
Dequeue:-
- As we know for for dequeue, we have remove element from root or from first position for that we have to move last element of array (here we have 1) at first position but still parent should have maximum value than child for that we have compare Number[i] with Number[2*i] and Number[2*i+1] because of you again go through upper image than you will that parent (Number[i]) has two child Number[2*i] and Number[2*i+1].So we have to compare that value and if you find and maximum value of child than parent that swap those two value.
Peek:-
- In peek we have where first element of array or tree.
Algorithm Of Max heap
Download :- Max Heap