COP3502_29b_Heaps2

# COP3502_29b_Heaps2 - Heaps & Priority Queues Computer...

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

Computer Science Department University of Central Florida Priority Queues COP 3502 – Computer Science I

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

View Full Document
page 2 Binary Heaps Building a Heap from scratch (a Max heap) Given: an unsorted list of n values 54, 87, 27, 67, 19, 31, 29, 18, 32, 56, 7, 12, 31 How can we build a heap from these values? It is really just a series of “insertions” Simply insert the n elements into the heap in the order that they arrive (in our case, from left to right) WHILE there are more elements: 1) Insert the next element 2) Percolate Up to a suitable position Once all elements are inserted, we have our heap
page 3 Binary Heaps Building a Heap from scratch (a Max heap) Given: an unsorted list of n values 54, 87, 27, 67, 19, 31, 29, 18, 32, 56, 7, 12, 31 54 54 87 87 54 87 54 27 87 54 27 67 87 67 27 54 87 67 27 54 19

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

View Full Document
page 4 Binary Heaps Building a Heap from scratch (a Max heap) Given: an unsorted list of n values 54, 87, 27, 67, 19, 31, 29, 18, 32, 56, 7, 12, 31 27 87 67 54 19 31 87 67 54 19 27 31
page 5 Binary Heaps Building a Heap from scratch (a Max heap) Given: an unsorted list of n values 54, 87, 27, 67, 19, 31, 29, 18, 32, 56, 7, 12, 31 18 31 87 67 54 19 27 29 31 87 67 54 19 27 29 32

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

View Full Document
page 6 Binary Heaps Building a Heap from scratch Running time: How long does it take to do one insertion? We just covered this! An insertion takes O(logn) As in the worst case, it has to Percolate all the way Up to root And we have n elements to insert Running time to make a heap from n elements is O(nlogn)
page 7 Binary Heaps Building a Heap from scratch Can we do better than O(nlogn) time? Turns out that we can Start by arbitrarily placing your elements into a complete binary tree Then, starting at the lowest level, Perform a Percolate Down (if necessary) So we work from the bottom and go up to the root Performing a Percolate Down at each node Only if necessary This function is known as Heapify

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

View Full Document
page 8 Binary Heaps Building a Heap from scratch Running time: Note: Realize that for any given complete tree, that is completely filled, the lowest level has ½ of the total nodes in a tree
This is the end of the preview. Sign up to access the rest of the document.

## This document was uploaded on 09/21/2011.

### Page1 / 34

COP3502_29b_Heaps2 - Heaps & Priority Queues Computer...

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

View Full Document
Ask a homework question - tutors are online