Unformatted text preview: er of variants however • Unlike a binary search tree, a heap is always a
complete tree! A min heap is
just the opposite • How does it do this? – By relaxing the ordering constraint – … children of nodes have smaller values (maxheap) – thus, the root always has the max value CPSC 223
Fall 2010 21 The Heap ADT
A (binary) “heap” is a complete binary tree such that: – Every parent node has a larger search key value than its
children (for maxheap) – Trivially, an empty tree is a heap 10 15 9 5 8 2 4 This is a heap 8 6 7 8 2 4 This is a not a heap … why? CPSC 223
Fall 2010 3 1 6 4 This is a not a heap … why? 22 11 10/21/10 The Heap ADT
The basic Heap ADT operations: // get the item with largest key in heap (alt ﬁndMin) Entry ﬁndMax(); // delete the item with the largest key in the heap void deleteMax(); // insert item into the heap void insert(const Entry& newItem); CPSC 223
Fall 2010 23 ArrayBased Heap Implementation
Because a heap is always complete we can “efﬁciently”
represent a heap using an array – If node n is stored at index i
– The children of n are stored at 2i+1 (left) and 2i+2 (right)
– The parent of n is at position Ⱥ(i–1)/2Ⱥ
10 we may have empty slots at the end … 9 8 10 9 5 2 4 8 5 2 4 0 2 3 4 5 1 CPSC 223
Fall 2010 6 24 12 10/21/10 ArrayBased Heap Implementation
• We assume that Heap has data members: Entry items[MAXITEMS]; // array of heap items int size;...
View
Full Document
 Fall '10
 ShawnBowers
 Algorithms, Binary Search, Sort, Binary heap, CPSC00, ArrayBased Heap Implementation

Click to edit the document details