The binary heaps have 2 properties:
As with AVL trees (remember the invariants?), an operation on a heap can destroy one of the properties, so a heap operation must not terminate until all heap properties are in order. This turns out to be simple to do.
A heap is a binary tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right. Such a tree is known as a complete binary tree.
A complete binary tree of height
Important Observation: Because a complete binary tree is so regular, it can be represented in an array and no links (or pointers) are necessary.
In the array representation, the element at position k represents a node in the tree whose child nodes will be at positions
Consider the following rules:
8, 3, 2, 1, 2, 1
1, 2, 3, 4, 5, 6, 7, 8
5, 8, 9, 7, 5, 4
3, 4, 3, 4, 4, 3, 5
insertX into the heap, we create a hole in the next available location, since otherwise, the tree will not be complete.X can be placed in the hole without violating heap order, then we do so and are done.X can be placed in the hole.insert(20)insert(20)insert(20)Verify with the parent (17)
insert(20)Verify with the parent (28)
insert(20)DONE!
insert(15)insert(15)insert(15)Verify with the parent (19)
insert(15)DONE!
deleteLet's consider the case of removing the root
Consider the implementation of heaps from Geeks for Geeks
heapify(int i) functionfind(int value) functiondelete(int value) functionThis material is genereated thanks to some extracts from following resources:
AI Overview