Created
February 21, 2017 09:46
-
-
Save shafiqshams/e8695da9773d75757aa5278edf217763 to your computer and use it in GitHub Desktop.
Insert The new element is initially appended to the end of the heap (as the last element of the array). The heap property is repaired by comparing the added element with its parent and moving the added element up a level (swapping positions with the parent). This process is called "percolation up". The comparison is repeated until the parent is …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//The following code example demonstrates the algorithm | |
public void insert(Comparable x) | |
{ | |
if(size == heap.length - 1) doubleSize(); | |
//Insert a new item to the end of the array | |
int pos = ++size; | |
//Percolate up | |
for(; pos > 1 && x.compareTo(heap[pos/2]) < 0; pos = pos/2 ) | |
heap[pos] = heap[pos/2]; | |
heap[pos] = x; | |
} | |
//The worst-case runtime of the algorithm is O(log n) | |
//since we need at most one swap on each level of a heap on the path from the inserted node to the root. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment