notes78

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

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

View Full Document Right Arrow Icon
Heaps A heap is an optimal implementation of a priority queue. insert(key) -> O(log n) removeMin() -> O(log n) A heap is a binary tree that stores in each node pairs (key,data). It satisfies two properties: Order Property: key(parent) <= key(child) Structural Property: All levels are full except the last one where all nodes are left-filled. Example Height of a Heap A tree with height h may store between:
Background image of page 1

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

View Full DocumentRight Arrow Icon
h = 3 h = 4 h = 3 h = 7 For a heap of height h=3 we can have a number of nodes 4 <= n <= 7. In general the number of elements are bound by: 2 h-1 <= n <= 2 h -1 After taking log 2 of both sides: 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 that is O(log(n)). Heap Insertion Original Heap
Background image of page 2
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. insert(key) in a heap takes time O(1) + O(log(n)) = O(log(n)) key::removemin() Remove minimum element
Background image of page 3

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

View Full DocumentRight Arrow Icon
Remove element on top of heap Removal will leave a hole. Replace hole with the last key of the heap. Now we fix the heap using a procedure called "downheap" where parent and children are swapped until the heap is fixed or we reach the bottom. After removing: After downheap: removeMin takes time O(1) + O(1) + O(log(n)) = O(log(n)) Implementation of a Heap Using an Array A binary tree can be represented in an array. A heap is also stored in this way.
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 10

notes78 - 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 Right Arrow Icon
Ask a homework question - tutors are online