|
| 1 | +#include<iostream> |
| 2 | +using namespace std; |
| 3 | +void heapify(int arr[], int n, int i){ |
| 4 | + int largest = i; |
| 5 | + int l = 2*i + 1; |
| 6 | + int r = 2*i + 2; |
| 7 | + |
| 8 | + //If left child is larger than root |
| 9 | + if (l < n && arr[l] > arr[largest]) |
| 10 | + largest = l; |
| 11 | + //If right child largest |
| 12 | + if (r < n && arr[r] > arr[largest]) |
| 13 | + largest = r; |
| 14 | + //If root is nor largest |
| 15 | + if (largest != i){ |
| 16 | + swap(arr[i], arr[largest]); |
| 17 | + //Recursively heapifying the sub-tree |
| 18 | + heapify(arr, n, largest); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +void heapSort(int arr[], int n){ |
| 23 | + for (int i = n / 2 - 1; i >= 0; i--) |
| 24 | + heapify(arr, n, i); |
| 25 | + //One by one extract an element from heap |
| 26 | + for (int i=n-1; i>=0; i--){ |
| 27 | + //Moving current root to end |
| 28 | + swap(arr[0], arr[i]); |
| 29 | + //Calling max heapify on the reduced heap |
| 30 | + heapify(arr, i, 0); |
| 31 | + } |
| 32 | +} |
| 33 | + //Function to print array |
| 34 | +void display(int arr[], int n){ |
| 35 | + for (int i = 0; i < n; i++){ |
| 36 | + cout << arr[i] << "\t"; |
| 37 | + } |
| 38 | + cout << "\n"; |
| 39 | +} |
| 40 | +int main(){ |
| 41 | + int arr[] = {1, 14, 3, 7, 0}; |
| 42 | + int n = sizeof(arr)/sizeof(arr[0]); |
| 43 | + cout << "Unsorted array \n"; |
| 44 | + display(arr, n); |
| 45 | + heapSort(arr, n); |
| 46 | + cout << "Sorted array \n"; |
| 47 | + display(arr, n); |
| 48 | +} |
| 49 | + |
| 50 | +/*Time Complexcity |
| 51 | +Best |
| 52 | +O(nlog n) |
| 53 | +
|
| 54 | +Average |
| 55 | +O(nlog n) |
| 56 | +
|
| 57 | +Worst |
| 58 | +O(nlog n) |
| 59 | +*/ |
0 commit comments