{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

lecture23

# lecture23 - COMP 250 Winter 2010 23 building a heap(slow...

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

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 i as a function of i . See thick solid curves. We give two plots: from

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}