Lecture
Lecture
Dr Zhouxiang Fei
Objectives
Learn, understand and implements the following data structures and concepts:
● Priority Queues
● Heap
● Heap Operations
● Heap Sorting
● Complexity of Heap Operations
Priority Queues
A data structure where elements are assigned priorities, and elements with higher
priority are dequeued first.
Examples:
Complete binary tree Complete binary tree Incomplete binary tree Incomplete binary tree
Heap as a Tree
Case 1
• root of tree: first element in the array, corresponding to i = 1
• parent(i) = floor(i/2): returns index of node's parent
• left(i) = 2i: returns index of node's left child
• right(i) = 2i + 1: returns index of node's right child
Heap as a Tree
Case 2
• root of tree: first element in the array, corresponding to i = 0
• parent(i) = floor[(i - 1)/2]: returns index of node's parent
• left(i) = 2i + 1: returns index of node's left child
• right(i) = 2i + 2: returns index of node's right child
Heap as a Tree
Case 2
• root of tree: first element in the array, corresponding to i = 0
• parent(i) = floor[(i - 1)/2]: returns index of node's parent
• left(i) = 2i + 1: returns index of node's left child
• right(i) = 2i + 2: returns index of node's right child
Heap as a Tree
Case 2
• root of tree: first element in the array, corresponding to i = 0
• parent(i) = floor[(i - 1)/2]: returns index of node's parent
• left(i) = 2i + 1: returns index of node's left child
• right(i) = 2i + 2: returns index of node's right child
Height of a Heap
Height of a heap with n nodes is ~log(n) (discuss in detail in seminar)
Insertion in a Heap
Insert. Add node at end, then swim it up.