Advertisement
CHU2

Minimum Heap Sort

Apr 3rd, 2023
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | Source Code | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void heapify(int array[], const int, int);
  6. void printarray(int array[], const int);
  7. void heapsort(int array[], const int);
  8.  
  9. int main() {
  10.     const int size = 6;
  11.     int array[size] = { 77, 15, 91, 21, 6, 46 };        //given values but to be sorted using minimum
  12.  
  13.     cout << "\nGiven: ";
  14.     printarray(array, size);
  15.  
  16.     for (int h = size / 2; h >= 0; h--) {
  17.         heapify(array, size, h);
  18.     }
  19.  
  20.     cout << "\nHeapified: ";
  21.     printarray(array, size);
  22.  
  23.     heapsort(array, size);
  24.  
  25.     cout << "\nSorted: ";
  26.     printarray(array, size);        //seems like it prints the sorted array backwards when uaing the smallest as the pivot or something
  27.  
  28.     return 0;
  29. }
  30.  
  31. void heapify(int array[], const int size, int h) {
  32.     int smallest = h;       //declare smallest
  33.     int low = (2 * h) + 1;
  34.     int high = (2 * h) + 2;
  35.  
  36.     if (low < size && array[low] < array[smallest]) {       //if left child is smaller than the root
  37.         smallest = low;
  38.     }
  39.     if (high < size && array[high] < array[smallest]) {     //if right child is smaller than "smallest", also it seems like <else if> statement doesn't work here, only <if if>
  40.         smallest = high;
  41.     }
  42.  
  43.     if (smallest != h) {        //if smallest is not root
  44.         swap(array[h], array[smallest]);
  45.         heapify(array, size, smallest);
  46.     }
  47. }
  48.  
  49. void printarray(int array[], const int size) {
  50.     for (int h = 0; h < size; h++) {
  51.         cout << array[h] << ' ';
  52.     }
  53. }
  54.  
  55. void heapsort(int array[], const int size) {
  56.     for (int h = size / 2; h >= 0; h--) {
  57.         heapify(array, size, h);
  58.     }
  59.     for (int h = size -1; h >= 0; h--) {
  60.         swap(array[0], array[h]);
  61.         heapify(array, h, 0);
  62.     }
  63. }
  64.  
  65. /*
  66. Heapified tree:
  67.      6
  68.     / \
  69.   15   46
  70.   /\    /
  71. 21 71   91
  72. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement