|
| 1 | +/*This implementation uses a vector<int> to store the elements to be sorted. The heapify function is used to create a max heap and maintain the heap property. The heapSort function performs the heap sort algorithm by repeatedly extracting the maximum element from the heap. Finally, the printArray function is a utility function to print the elements of an array.*/ |
| 2 | +/* time complexity O(n log n) |
| 3 | + Space complexity O(1) */ |
| 4 | +#include <iostream> |
| 5 | +#include <vector> |
| 6 | + |
| 7 | +using namespace std; |
| 8 | + |
| 9 | +void heapify(vector<int>& arr, int n, int i) { |
| 10 | + int largest = i; // Initialize largest as root |
| 11 | + int left = 2 * i + 1; // Left child |
| 12 | + int right = 2 * i + 2; // Right child |
| 13 | + |
| 14 | + // If left child is larger than root |
| 15 | + if (left < n && arr[left] > arr[largest]) |
| 16 | + largest = left; |
| 17 | + |
| 18 | + // If right child is larger than largest so far |
| 19 | + if (right < n && arr[right] > arr[largest]) |
| 20 | + largest = right; |
| 21 | + |
| 22 | + // If largest is not root |
| 23 | + if (largest != i) { |
| 24 | + swap(arr[i], arr[largest]); |
| 25 | + |
| 26 | + // Recursively heapify the affected sub-tree |
| 27 | + heapify(arr, n, largest); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +void heapSort(vector<int>& arr) { |
| 32 | + int n = arr.size(); |
| 33 | + |
| 34 | + // Build heap (rearrange array) |
| 35 | + for (int i = n / 2 - 1; i >= 0; i--) |
| 36 | + heapify(arr, n, i); |
| 37 | + |
| 38 | + // One by one extract an element from heap |
| 39 | + for (int i = n - 1; i > 0; i--) { |
| 40 | + // Move current root to end |
| 41 | + swap(arr[0], arr[i]); |
| 42 | + |
| 43 | + // call max heapify on the reduced heap |
| 44 | + heapify(arr, i, 0); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// Utility function to print an array |
| 49 | +void printArray(const vector<int>& arr) { |
| 50 | + for (int i = 0; i < arr.size(); ++i) |
| 51 | + cout << arr[i] << " "; |
| 52 | + cout << endl; |
| 53 | +} |
| 54 | + |
| 55 | +int main() { |
| 56 | + vector<int> arr = {12, 11, 13, 5, 6, 7}; |
| 57 | + cout << "Original array: "; |
| 58 | + printArray(arr); |
| 59 | + |
| 60 | + heapSort(arr); |
| 61 | + |
| 62 | + cout << "Sorted array: "; |
| 63 | + printArray(arr); |
| 64 | + |
| 65 | + return 0; |
| 66 | +} |
0 commit comments