lecture24

lecture24 - COMP 250 Winter 2010 24 - building a heap...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon

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

View Full DocumentRight Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: COMP 250 Winter 2010 24 - building a heap (fast), heapsort 3/12/2010 (modified 3/22) Building a heap in O ( n ) (fast) In the last two lectures we discussed a method for building a heap which, in the worst case, took about n log n swaps. But suppose you want to build a heap very quickly. For example, you might be using the heap to implement a priority queue, and from time to time you want to change the definition of how any two keys/nodes are compared. This requires that you rebuild the priority queue (heap), based on the new comparison definition. So lets now look at a faster method for building a heap. We start off with a complete binary tree with n nodes and a definition for ordering these nodes, but we make no assumption about the present state of the ordering. We want to take these nodes and build a heap. [paragraph modified 3/22] The buildHeap() algorithm from lecture 22 built a heap from the top down by swapping elements up the heap from child to parent. Given that the first i 1 elements already defined a heap, it compared the i th element to its parent (and grandparent, etc, if need be) and carries out a sequence of swaps. Worst case was that the i-th element had to climb log i steps to the root. The faster buildHeap algorithm goes in the opposite direction(s). We build a heap from the bottom up , by swapping elements down the heap toward the leaves. The fast buildHeap algorithm is based on the following downHeap algorithm, which takes a complete binary tree that is represented as an array a and an index i (where 1 i n ). Suppose this binary tree has the property that node i s two children (if they exist) are heaps, but the subtree rooted at i might itself not be a heap because i might be greater than at least one of its children. The operation downHeap turns the tree rooted at i into a heap (by swapping...
View Full Document

Page1 / 4

lecture24 - COMP 250 Winter 2010 24 - building a heap...

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

View Full Document Right Arrow Icon
Ask a homework question - tutors are online