Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int n;
- vector<int> heap;
- void print_heap(){
- for(auto i: heap){
- cout << i << " ";
- }
- cout << '\n';
- }
- void down_heap(int idx, int size){
- int l = (idx*2)+1;
- int r = (idx*2)+2;
- int mx_idx = idx;
- //int size = heap.size();
- if(l<size && heap[l]>heap[mx_idx]){
- //cout << "HI" << '\n';
- mx_idx = l;
- }
- if(r<size && heap[r]>heap[mx_idx]){
- mx_idx = r;
- }
- if(mx_idx != idx){
- swap(heap[idx], heap[mx_idx]);
- down_heap(mx_idx, size);
- }
- }
- int main(){
- //freopen("heapsorting.in", "r", stdin);
- cin >> n;
- heap.resize(n);
- for(int i=0; i<n; i++){
- cin >> heap[i];
- }
- for(int i=n/2-1; i>=0; i--){
- down_heap(i, heap.size());
- //print_heap();
- //cout << "=====" << '\n';
- }
- for(int i=n-1; i>=0; i--){
- swap(heap[i], heap[0]);
- down_heap(0, i);
- //down_heap(0, i-1); //!!problem cause invalid data
- }
- print_heap();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement