notes77

# notes77 - Heaps A heap is an optimal implementation of a...

This preview shows pages 1–5. Sign up to view the full content.

2/14/05, 2/16/05, 2/18/05 Heaps A heap is an optimal implementation of a priority queue in which the function insert(key) takes O(log n) time and the function removeMin() takes O(log n) time. A heap is a binary tree that stores (key, data) pairs in each node. Heaps satisfy two properties: 1) The order property - The key of the parent is less than or equal to the key of the child. i.e. key(parent) <= key(child) 2) The structural property - All levels are full except the last one in which all nodes are left filled. The below is an example of a heap that meets the above properties. The below is not a heap. It satisfies the order property, but it does not satisfy the structural property because it is not left filled.

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
The following is also not a heap. It satisfies the structural property, but the four is greater than the three, which is one of it's children, and thus it does not satisfy the order property. Height of a Heap This is a tree of height h with the minimum number of elements, where h = 3 and n = 4, where n is the number of nodes. This tree has a height of 3 with the maximum number of elements, which is seven. Thus, h = 3 and n = 7.
For a heap of height h = 3, we can have a number of nodes, n, such that 4 <= n <= 7. In general , 2 h-1 <= n <= 2 h -1 Now, we take log 2 of both sides and find: log 2 (2 h-1 ) <= log 2 (n) <= log 2 (2 h -1) log 2 (2 h-1 ) <= log 2 (n) <= log 2 (2 h ) h-1 <= log 2 n <= h h = O(log(n)) Therefore, the height of a heap is O(log n). This result is important because insert() and removeMin() take time proportional to the height. In other words, the removeMin and insert functions take O(log n) time. Heap Insertion Assume the following is our original heap. Now, we call - insert(2). We will add a new element to the next available position. This should take O(1) time assuming we have a pointer to the next available position. After inserting the 2, we will get the below tree:

This preview has intentionally blurred sections. Sign up to view the full version.

View Full Document
But, this is not a heap since the child, 2, is smaller than it's parent, 7. This violates the order property. Therefore, after inserting we will fix the heap using a process called "upheap" by swapping parent and child as needed or until we reach the root. We start by swapping the two and the seven. But, this is still not a heap, since the 3 node is the parent of the 2 node and 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### Page1 / 13

notes77 - Heaps A heap is an optimal implementation of a...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online