The Java Course provides a general introduction to programming in Java. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. 
Home Heap Heap Insert  
See also: Heap Remove  
Search the VIAS Library  Index  
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. Again, to guarantee completeness, we add the new element at the bottommost, rightmost position in the tree, which is the next available space in the array. 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 