堆排序求调
查看原帖
堆排序求调
1528563
lyt_tcsn楼主2025/1/12 19:19
#include <bits/stdc++.h>
using namespace std;
class Heap {
    int a[100005];
public:
    int size = 0;
    Heap() {}
    int top() { return a[1]; }
    void push(int x) {
        a[++size] = x;
        x = size;
        while (x != 1 && a[x] > a[x / 2]) {
            swap(a[x], a[x / 2]);
            x /= 2;
        }
    }
    void pop() {
        swap(a[1], a[size--]);
        int x = 1;
        while (x * 2 <= size) {
            int tmp = x * 2;
            if (tmp + 1 <= size) {
                tmp = a[tmp] < a[tmp + 1] ? tmp : tmp + 1;
            }
            if (a[x] > a[tmp]) {
                swap(a[x], a[tmp]);
                x = tmp;
            }
            else break;
        }
    }
};
int main() {
    int a, n;
    scanf("%d", &n);
    Heap h;
    while (n--) {
        scanf("%d", &a);
        h.push(a);
    }
    while (h.size != 0) {
        printf("%d ", h.top());
        h.pop();
    }
    return 0;
}
2025/1/12 19:19
加载中...