
Heap before inserting the value 3 

Heap after inserting the value 3 
$64,000 question:

Insert a node containing the insertion value in the "fartest left location" of the lowest level of the Binary Tree Filter the inserted node up using this algorithm: while ( inserted node's value < value in its parent node ) { swap the values of the respective node; } 

void put( double x ) { a[NNodes+1] = x; // Insert x in the "fartest left location" // This preserves the "complete bin tree" prop NNodes++; // We have 1 more node HeapFilterUp( NNodes ); // Filter the inserted node // The FilterUp() method need to know // which node is the inserted node !!! // The parameter NNodes identifies the // inserted node a[NNodes] } 
HeapFilterUp( k ) // Filter up the node a[k] { while ( k has a parent node ) { parent = k/2; // a[parent] is the parent node of a[k] if ( a[k] < a[parent] ) { swap a[k] <> a[parent]; k = parent; } else { break; // a[k] is in correct position, DONE ! } } 
/* =================================================== HeapFilterUp(k): Filters the node a[k] up the heap =================================================== */ void HeapFilterUp( int k ) { int parent; // parent = parent node of k double help; // Used for swapping while ( parent > 0 ) // parent == 0 means no parent { parent = k/2; // Find parent node of k if ( a[k] < a[parent] ) { /* ===================================== Wrong order: swap a[k] and a[parent] ===================================== */ help = a[parent]; a[parent] = a[k]; a[k] = help; /*  Continue one level in the tree  */ k = parent; } else { break; // k is in correct position  DONE ! } } } 
How to run the program:



Example:

Running time( insert(n) ) = Running time heap insert in heap with n node = height of a heap of n nodes 


Proof:

Therefore:
Let: n = # nodes in heap of height h 2^{h}  1 < n ≤ 2^{h+1} − 1 <===> 2^{h} < n + 1 ≤ 2^{h+1} <===> h < lg(n + 1) ≤ h+1 ===> height of heap ~= lg(n + 1) 

