idastan97

ACM Heap-Max/Heap sort (Stack)

Oct 6th, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.84 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. vector<int> heap;
  6.  
  7. void insert(int x){
  8.     heap.push_back(x);
  9.     int v=heap.size()-1;
  10.     while (v>1){
  11.         if (heap[v]>heap[v/2]) swap(heap[v], heap[v/2]);
  12.         else break;
  13.         v/=2;
  14.     }
  15. }
  16.  
  17. int getMax(){
  18.     int res=heap[1];
  19.     heap[1]=heap.back();
  20.     heap.pop_back();
  21.     int v=1;
  22.     while (v<heap.size()){
  23.         int l=v*2, r=v*2+1;
  24.         if (l<heap.size()){
  25.             if (r<heap.size() && heap[r]>heap[l]){
  26.                 l=r;
  27.             }
  28.             if (heap[v]<heap[l]) {
  29.                 swap(heap[v], heap[l]);
  30.             }
  31.             v=l;
  32.         } else break;
  33.     }
  34.     return res;
  35. }
  36.  
  37. int main() {
  38.     heap.push_back(0);
  39.     int i, n=5;
  40.     for (i=0; i<n; i++){
  41.         int x;
  42.         cin>>x;
  43.         insert(x);
  44.     }
  45.     vector<int> stack;
  46.     for (i=0; i<n; i++){
  47.         stack.push_back(getMax());
  48.     }
  49.     for (i=0; i<n; i++){
  50.         cout<<stack.back()<<" ";
  51.         stack.pop_back();
  52.     }
  53.    
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment