Understanding Heapsort: Efficiency and Max-Heap Construction in Sorting Algorithms
This lecture discusses the fundamentals of sorting algorithms, specifically focusing on Insertion Sort, Merge Sort, and Heapsort. We delve into the efficiency of these algorithms and their running time from input to output. Key concepts covered include the definition of a heap, the Max-Heapify procedure, and the process of building a heap. The lecture provides detailed examples, including input sequences and step-by-step max-heap construction, to illustrate how Heapsort operates and its importance in data structure optimization.
Understanding Heapsort: Efficiency and Max-Heap Construction in Sorting Algorithms
E N D
Presentation Transcript
Sorting Problem e.g., Insertion Sort, Merge Sort
Efficiency • Running time from receiving the input to producing the output. Running time Insertion Sort Merge Sort
Heapsort • Heap, a data structure • Max-Heapify procedure • Building a heap • Heapsort
A Data Structure Heap • A heap is an array object that can be viewed as a nearly complete binary tree. 1 6 2 3 5 3 6 5 3 2 4 1 4 5 6 2 4 1
Max-Heapify • Max-Heapify(A,i) is a subroutine. • When it is called, two subtrees rooted at Left(i) and Right(i) are max-heaps, but A[i] may not satisfy the max-heap property. • Max-Heapify(A,i) makes the subtree rooted at A[i] become a max-heap by letting A[i] “float down”.
4 14 7 4 14 7 2 8 1 2 8 1 14 8 7 2 1 4
Building a Heap e.g., 4, 1, 3, 2, 16, 9, 10, 14, 8, 7.
4 1 3 10 9 2 16 8 7 14 Proof.
4 1 3 10 9 2 16 8 7 7 14
4 1 3 10 9 2 16 8 7 14
4 1 3 10 9 2 16 8 7 14
Building a Max-Heap e.g., 4, 1, 3, 2, 16, 9, 10, 14, 8, 7.
4 1 3 10 9 2 16 8 7 14
4 1 3 10 9 2 16 8 7 14
4 1 3 10 9 16 14 2 8 7
4 1 3 10 9 14 16 2 8 7
4 1 10 3 9 14 16 2 8 7
4 1 10 3 9 14 16 2 8 7
4 16 10 3 9 14 1 2 8 7
4 16 10 3 9 14 7 2 8 1
16 4 10 3 9 14 7 2 8 1
16 14 10 3 9 4 7 2 8 1
16 14 10 3 9 7 8 2 4 1
16 14 10 3 9 7 8 2 4 1
Input: 4, 1, 3, 2, 16, 9, 10, 14, 8, 7. Build a max-heap 16 14 10 3 9 7 8 2 4 1 16, 14, 10, 8, 7, 9, 3, 2, 4, 1.
1 14 10 3 9 7 8 2 4 16
1 14 10 3 9 7 8 2 4 16 1, 14, 10, 8, 7, 9, 3, 2, 4, 16.
14 8 10 3 9 7 4 2 1 16
14 8 10 3 9 7 4 2 1 16 14, 8, 10, 4, 7, 9, 3, 2, 1, 16.
1 8 10 3 9 7 4 2 14 16
1 8 10 3 9 7 4 2 14 16 1, 8, 10, 4, 7, 9, 3, 2, 14, 16.
10 8 9 3 1 7 4 2 14 16
10 8 9 3 1 7 4 2 14 16 10, 8, 9, 4, 7, 1, 3, 2, 14, 16.
2 8 9 3 1 7 4 14 16 10
2 8 9 3 1 7 4 14 16 10 2, 8, 9, 4, 7, 1, 3, 10, 14, 16.
9 8 3 2 1 7 4 14 16 10
9 8 3 2 1 7 4 14 16 10 9, 8, 3, 4, 7, 1, 2, 10, 14, 16.
2 8 3 9 1 7 4 14 16 10
8 7 3 9 2 1 4 14 16 10
1 7 3 9 2 8 4 14 16 10
7 4 3 9 2 8 1 14 16 10