838. 堆排序

手写堆排序。

const int N=1e5+10;
int heap[N],cnt;
int n,m;

void down(int u)
{
    int j=u*2;
    while(j <= n)
    {
        if(j < n && heap[j] > heap[j+1])
            j++;
        if(heap[u] > heap[j])
        {
            swap(heap[u],heap[j]);
            u=j;
            j=u*2;
        }
        else
            break;
    }
}

void createHeap()
{
    for(int i=n/2;i>=1;i--)
        down(i);
}

int main()
{
    cin>>n>>m;

    for(int i=1;i<=n;i++) cin>>heap[i];

    createHeap();

    while(m--)
    {
        cout<<heap[1]<<' ';
        swap(heap[1],heap[n--]);
        down(1);
    }
    //system("pause");
    return 0;
}
posted @ 2021-03-11 20:37  Dazzling!  阅读(36)  评论(0编辑  收藏  举报