The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
Home Heap Heap Insert | ||
Heap Insert
Inserting a new item in a heap is a similar operation, except that instead of trickling a value down from the top, we trickle it up from the bottom.
Then to restore the heap property, we compare the new value with its neighbors. The situation looks like this: The new value is c. We can restore the heap property of this subtree by comparing c to a. If c is smaller, then the heap property is satisfied. If c is larger, then we swap c and a. The swap satisfies the heap property because we know that c must also be bigger than b, because c > a and a > b. Now that the subtree is reheapified, we can work our way up the tree until we reach the root.
|
||
Home Heap Heap Insert |