DSA Lab Manual (Heap Sort)
DSA Lab Manual (Heap Sort)
Algorithms (DSA)
Lab Topic: Heap Sort
Objectives:
1. Understand the concept of heap data structures (max heap and min heap).
2. Implement heap sort algorithm in C++.
3. Analyze the time complexity of heap sort.
Heap sort is a comparison-based sorting algorithm that uses a binary heap data structure. It
involves the following steps:
A max heap is a binary tree where the parent node is always greater than or equal to its
child nodes.
In an array representation of a heap, for a node at index i:
o Left child is at index 2*i + 1.
o Right child is at index 2*i + 2.
o Parent node is at index (i-1)/2.
Algorithm Steps:
C++ Implementation:
#include <iostream>
#include <vector>
using namespace std;
// Main function
int main() {
vector<int> arr = {12, 11, 13, 5, 6, 7};
cout << "Original array: \n";
printArray(arr);
heapSort(arr);
return 0;
}
Sample Output:
Original array:
12 11 13 5 6 7
Sorted array:
5 6 7 11 12 13
Practice Questions:
1. Modify the heap sort algorithm to sort the array in descending order.
2. Write a function to build a min heap instead of a max heap.
3. Explain the differences between heap sort and merge sort in terms of performance and
use cases.
Conclusion:
Heap sort is an efficient, in-place, and non-stable sorting algorithm. It is widely used in scenarios
requiring guaranteed O(n log n) performance without additional memory allocation.