Advertisement
tepyotin2

Heap Sorting

May 18th, 2025
443
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int n;
  6. vector<int> heap;
  7.  
  8. void print_heap(){
  9.     for(auto i: heap){
  10.         cout << i << " ";
  11.     }
  12.     cout << '\n';
  13. }
  14.  
  15. void down_heap(int idx, int size){
  16.     int l = (idx*2)+1;
  17.     int r = (idx*2)+2;
  18.     int mx_idx = idx;
  19.     //int size = heap.size();
  20.     if(l<size && heap[l]>heap[mx_idx]){
  21.         //cout << "HI" << '\n';
  22.         mx_idx = l;
  23.     }
  24.     if(r<size && heap[r]>heap[mx_idx]){
  25.         mx_idx = r;
  26.     }
  27.     if(mx_idx != idx){
  28.         swap(heap[idx], heap[mx_idx]);
  29.         down_heap(mx_idx, size);
  30.     }
  31. }
  32.  
  33. int main(){
  34.     //freopen("heapsorting.in", "r", stdin);
  35.    
  36.     cin >> n;
  37.     heap.resize(n);
  38.     for(int i=0; i<n; i++){
  39.         cin >> heap[i];
  40.     }
  41.     for(int i=n/2-1; i>=0; i--){
  42.         down_heap(i, heap.size());
  43.         //print_heap();
  44.         //cout << "=====" << '\n';
  45.     }
  46.     for(int i=n-1; i>=0; i--){
  47.         swap(heap[i], heap[0]);
  48.         down_heap(0, i);
  49.         //down_heap(0, i-1); //!!problem cause invalid data
  50.     }
  51.     print_heap();
  52.    
  53.     return 0;
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement