Heap Sort
Heap Sort
Queue
CSE 2215 - Lecture 12 - Summer 2023
Instructor : Fahmid Al Rifat, Lecturer, Dept. of CSE , UIU
[email protected] 1
Binary Heaps
The (binary) heap data structure is an array object that can be viewed as a complete binary tree
Each node of the tree corresponds to an element of the array that stores the value in the node.
The tree is completely filled on all levels except possibly the lowest, where it is filled from the left up
to a point.
2
Binary Heaps
3
Types of Binary Heaps
4
The Min-Heap Property
5
The Max-Heap Property
6
Max-Heap Operations: Max-Heapify()
Max-Heapify(): maintain the max-heap property
Given: a node i in the heap with children l and r
Action: let the value of the parent node “float down” so subtree at i satisfies the heap property
7
Max-Heap Operations: Max-Heapify()
8
Heapify() - Example
9
Heapify() - Example
10
Heapify() - Example
11
Heapify() - Example
12
Heapify() - Example
13
Heapify() - Example
14
Heapify() - Example
15
Heapify() - Example
16
Heapify() - Example
17
Analyzing Heapify()
Fixing up relationships among the elements A[i], A[l], and A[r] takes O(1) time
Ifthe heap at i has n elements, at most how many elements can the subtrees at l or r
have?
19
Heap Operations: BuildHeap()
20
Heap Operations: BuildHeap()
• Converts an unorganized array A into a max-heap.
21
BuildHeap(): Example
22
BuildHeap(): Example
23
BuildHeap(): Example
24
BuildHeap(): Example 2
Workthrough example
A = {14, 11, 33, 22, 56, 49, 30, 24, 18, 37}
Construct a Min-Heap from the given array using Build-Heap function.
25
Analyzing BuildHeap()
26
Analyzing BuildHeap(): Tight
To Heapify() a subtree takes O(h) time, where h is the height of the
subtree
h = O(log m), m = # nodes in the subtree
27
HeapSort
28
HeapSort
Heapsort(A)
{
BuildHeap(A);
for (i = length(A) downto 2)
{
Swap(A[1], A[i]);
heap_size(A) = heap_size(A) - 1;
Heapify(A, 1);
}
}
29
HeapSort
30
Analyzing HeapSort
31
Priority Queue
or key
Supports the operations Insert(), Maximum(), and ExtractMax()
32
Priority Queue Operations
• Maximum( S ) – Returns, but does not remove, the element of S with the largest key
• Extract-Max( S ) – Removes and returns the element of S with the largest key
• Increase-Key( S, x, k ) – Increases the value of element x’s key to the new value k
33
Priority Queue Operations
34
Priority Queue Operations
35
Priority Queue Operations
36
Priority Queue Operations
37
Thank You
38