Skip to content

Instantly share code, notes, and snippets.

@shafiqshams
Created February 21, 2017 09:46
Show Gist options
  • Save shafiqshams/e8695da9773d75757aa5278edf217763 to your computer and use it in GitHub Desktop.
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 …
//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