堆排序

#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 20;
const int mod = 1e9 + 7;
#define ll long long
#define P pair<int,int>
#define mk make_pair
int heap[N];
int n;
void downAdjust(int low,int high)
{
    int i = low,j = i * 2;
    while(j <= high)
    {
        if(j + 1 <= high && heap[j] < heap[j+1])
        {
            j++;
        }
        if(heap[j] > heap[i])
        {
            swap(heap[j],heap[i]);
            i = j;
            j = i * 2;
        }
        else
        {
            break;
        }
    }

}
void createHeap()
{
    for(int i=n/2;i>=1;i--)
    {
        downAdjust(i,n);
    }
}
int main() {
    cin >> n;
    for (int i = 1; i <= n; i++) {
        cin >> heap[i];
    }
    createHeap();
    for (int i = n; i > 1; i--) {
        swap(heap[i], heap[1]);
        downAdjust(1, i - 1);
    }
    for(int i=1;i<=n;i++)
    {
        cout << heap[i] << " ";
    }



    return 0;
}
/*
6
6 1 2 7 2 8
14
 */
posted @ 2021-04-12 16:06  hh13579  阅读(30)  评论(0编辑  收藏  举报