手写堆排序

#include<bits/stdc++.h>
using namespace std;

const int maxn = 100000;
int heap[maxn], n;

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

}

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

int removeMax()
{
    int x = heap[1];
    heap[1] = heap[n];
    n--;
    SHIFT_DOWN(1);
    return x;
}

int main()
{
    scanf("%d", &n);
    for(int i = 1;i <= n;i++)
        scanf("%d", &heap[i]);
    makeheap();
    while(n)
    {
        cout << removeMax() << " ";
    }
}

字节面试没写出来,草。

posted @ 2020-04-02 12:03  Rogn  阅读(376)  评论(2编辑  收藏  举报