This preview shows pages 1–2. Sign up to view the full content.
This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: COMP 250 Winter 2010 23 - building a heap (slow) March 10, 2010 Worst case for building a heap (using slow algorithm) The algorithm I presented last lecture for building a heap is relatively inefficient in the worst case. (We will see a faster algorithm next lecture.) Let’s see why it is inefficient. If we label the nodes from i = 1 to i = n , then if node i is at level l (the root is at level l = 0), we can see by inspection (see lecture slides) that 2 l ≤ i ≤ 2 l +1 − 1 and so ⌊ log i ⌋ = l . Thus, when we add node i to the heap, we need to do at most ⌊ log i ⌋ swaps up the tree to bring the new element i to a position where it is greater than its parent. In the worst case, the element at i is smaller than all its ancesters and we need to swap it ⌊ log i ⌋ times, which brings it to the root. Since we are adding n nodes in total, the worst case number of swaps is: t ( n ) = n summationdisplay i =1 ⌊ log i ⌋ To understand this sum, we ignore the floor and we plot the log...
View Full Document
This note was uploaded on 09/25/2011 for the course COMP 250 taught by Professor Blanchette during the Spring '08 term at McGill.
- Spring '08
- Computer Science