|
| 1 | +/* |
| 2 | +Heap sort is a sorting technique based on comparison based on binary heap data. |
| 3 | +Similar to sorting, it finds the largest number first and then puts the largest number last. |
| 4 | +
|
| 5 | +
|
| 6 | +This sorting algorithm uses a tree structure called the stack, where the stack is a kind of binary tree. |
| 7 | +A binary decision tree in which the value of the root of a tree is less than or equal to the value of one of its roots is called a min-heap. |
| 8 | +A decision binary tree is called maximum heap when the value of the root of a tree is greater than or equal to the value of one of its trees. |
| 9 | +In this post, we'll learn more about C++ Stack Sorting. |
| 10 | +
|
| 11 | +Working of heap sort in C++ |
| 12 | +To sort any list into a logical order following steps are followed:- |
| 13 | +
|
| 14 | +Convert the list into a heap. |
| 15 | +Now convert this heap into a max heap. |
| 16 | +As the heap is converted to max heap largest element in the list is stored in the root of the heap, replace it with the last item of the heap. |
| 17 | +Now delete this node and reduce the size of the heap by 1. |
| 18 | +Follow these steps until the list is sorted. |
| 19 | +*/ |
| 20 | + |
| 21 | +#include<iostream> |
| 22 | +using namespace std; |
| 23 | +void heapify(int arr[], int n, int i){ |
| 24 | + int largest = i; |
| 25 | + int l = 2*i + 1; |
| 26 | + int r = 2*i + 2; |
| 27 | + |
| 28 | + //If left child is larger than root |
| 29 | + if (l < n && arr[l] > arr[largest]) |
| 30 | + largest = l; |
| 31 | + //If right child largest |
| 32 | + if (r < n && arr[r] > arr[largest]) |
| 33 | + largest = r; |
| 34 | + //If root is nor largest |
| 35 | + if (largest != i){ |
| 36 | + swap(arr[i], arr[largest]); |
| 37 | + //Recursively heapifying the sub-tree |
| 38 | + heapify(arr, n, largest); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +void heapSort(int arr[], int n){ |
| 43 | + for (int i = n / 2 - 1; i >= 0; i--) |
| 44 | + heapify(arr, n, i); |
| 45 | + //One by one extract an element from heap |
| 46 | + for (int i=n-1; i>=0; i--){ |
| 47 | + //Moving current root to end |
| 48 | + swap(arr[0], arr[i]); |
| 49 | + //Calling max heapify on the reduced heap |
| 50 | + heapify(arr, i, 0); |
| 51 | + } |
| 52 | +} |
| 53 | + //Function to print array |
| 54 | +void display(int arr[], int n){ |
| 55 | + for (int i = 0; i < n; i++){ |
| 56 | + cout << arr[i] << "\t"; |
| 57 | + } |
| 58 | + cout << "\n"; |
| 59 | +} |
| 60 | +int main(){ |
| 61 | + int arr[] = {1, 14, 3, 7, 0}; |
| 62 | + int n = sizeof(arr)/sizeof(arr[0]); |
| 63 | + cout << "Unsorted array \n"; |
| 64 | + display(arr, n); |
| 65 | + heapSort(arr, n); |
| 66 | + cout << "Sorted array \n"; |
| 67 | + display(arr, n); |
| 68 | +} |
| 69 | + |
| 70 | +/*Time Complexcity |
| 71 | +Best |
| 72 | +O(nlog n) |
| 73 | +
|
| 74 | +Average |
| 75 | +O(nlog n) |
| 76 | +
|
| 77 | +Worst |
| 78 | +O(nlog n) |
| 79 | +*/ |
0 commit comments