Lect9 - Heaps & Priority Queues A heap is a binary...

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

View Full Document Right Arrow Icon
1 A heap is a binary tree. A heap is best implemented in sequential representation (using an array). Two important uses of heaps are: (i) efficient implementation of priority queues (ii) sorting -- Heapsort.
Background image of page 1

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

View Full DocumentRight Arrow Icon
2 A Heap 10 20 30 40 50 25 55 52 42 Any node’s key value is less than its children’s.
Background image of page 2
3 Sequential Representation of Trees There are three methods of representing a binary tree using array representation. 1. Using index values to represent edges: class Node { Data elt; int left; int right; } Node; Node[] BinaryTree[TreeSize];
Background image of page 3

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

View Full DocumentRight Arrow Icon
4 Method 1: Example A D B C E G I Index Element Left Right 1 A 2 3 2 B 4 6 3 C 0 0 4 D 0 0 5 I 0 0 6 E 7 0 7 G 5 0
Background image of page 4
5 Method 2 2. Store the nodes in one of the natural traversals: class Node { StdElement elt; boolean left; boolean right; }; Node[] BinaryTree[TreeSize];
Background image of page 5

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

View Full DocumentRight Arrow Icon
6 Method 2: Example A D B C E G I Index Element Left Right 1 A T T 2 B T T 3 D F F 4 E T F 5 G T F 6 I F F 7 C F F Elements stored in Pre-Order traversal
Background image of page 6
7 Method 3 3. Store the nodes in fixed positions: (i) root goes into first index, (ii) in general left child of tree[i] is stored in tree[2i] and right child in tree[2i+1].
Background image of page 7

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

View Full DocumentRight Arrow Icon
8 Method 3: Example A D B C E G A B C D E - - - - G - 1 2 3 4 5 6 7 8 9 10 11 12
Background image of page 8
Heaps Heaps are represented sequentially using the third method. Heap is a complete binary tree : shortest-path length tree with nodes on the lowest level in their leftmost positions. Max-Heap has max element as root. Min-Heap has min element as root. The elements in a heap satisfy heap conditions: for
Background image of page 9

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

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

Page1 / 33

Lect9 - Heaps & Priority Queues A heap is a binary...

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

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