Data sturcture and algorithm week 9
Data sturcture and algorithm week 9
Semester – II Semester
EA2331201010152
1. State & explain the algorithm to perform Heap sort. Also analyze the time
complexity of the algorithm.
Heap sort is a comparison-based sorting algorithm that utilizes a heap data structure to
efficiently order elements. Here's the algorithm breakdown:
Steps:
1. Build a Max-Heap:
o Arrange the input data in a max-heap structure. In a max-heap, the parent node
is always greater than or equal to its children.
o You can use various methods to create a heap, including bottom-up heap
construction or using heapify operations.
2. Extract Maximum Repeatedly:
o Repeatedly perform the following:
▪ Swap the root element (largest in a max-heap) with the last element of the
heap.
▪ Reduce the heap size by 1 (exclude the last element).
▪ Heapify the remaining elements to maintain the max-heap property.
3. Result:
o After all extractions, the elements in the reduced heap will be in descending
order (largest at the beginning). Reversing this order provides the sorted data in
ascending order.
Time Complexity:
• Best Case: O(n log n) - This occurs when the input data is already sorted in
descending order (already a max-heap). The heapify operations for extraction take
logarithmic time (log n) and are repeated n times.
• Average Case: O(n log n) - For most random inputs, the average time complexity
remains the same as the best case. Building the heap and the extraction process with
heapify take n log n time on average.
• Worst Case: O(n log n) - This happens when the input data is sorted in ascending
order (opposite of a max-heap). Reversing the sorted elements after extraction takes
additional linear time (n), but the dominant factor is still the heap operations (n log n).
2. Construct Minheap structure for the initial key set 42, 23, 74,11,
65,58,94,36,99,87.
Ans. Constructing Min-Heap for [42, 23, 74, 11, 65, 58, 94, 36, 99, 87]
EA2331201010152
Steps:
Resulting Min-Heap:
11
/
EA2331201010152