SUNY Geneseo Department of Computer Science
{Date}
CSci 240, Spring 2007
Prof. Doug Baldwin
SOFIs
Read Section 14.4 intro (pp 493 bottom to 494)
Two kinds of heap
Examples
![[A Complete Tree Heap]](heap0420a.png)
Try to develop algorithm(s) for inserting a new value into a heap.
![[Heap Containing 2, 3, 6, and 9]](heap0420b.png)
insert( v )
make node from v
make this node a leaf of heap, in available spot closest to root
while v is less than parent (and v has a parent)
swap with parent
insert2( v )
if ( ! this.isEmpty() )
if ( v >= this.value )
if ( putleft )
putleft = left.insert(v )
return true
else
putleft = ! right.insert( v )
return false
else
swap v with this.value
this.insert( v ) // this is the old root value after swap
else
this.value = v; left = right = empty heap
return false
First version of "insert" above is pretty solid, but requires finding the empty leaf position "closest to root." This is a well-defined notion if the heap is a "complete" tree.
![[Tree with Top 3 Levels Filled and Left-Most 3 Nodes Present at Bottom]](completetree.png)
Hand out Problem Set 13
Representing complete trees
Read section 14.2.4