Insertion into Heap
insert will place a new element in the next available array position; this keeps the binary tree complete.
To maintain the heap order property, we must percolate up the new value until it reaches its proper position. This is easy: if the new item is less than its parent, swap the new item with its parent; then percolate up from the parent.
public void insert( AnyType item ) { if ( currentSize >= array.length - 1 ) enlargeArray( array.length * 2 + 1 ); int hole = ++currentSize; while ( hole > 1 && item.compareTo( array[hole / 2] ) < 0 ) { array[hole] = array[hole / 2]; // swap hole /= 2; } // change hole to parent array[hole] = item; }
This is simple and gives O(log(n)) insert.