这篇博客详细介绍了堆的基本操作,包括插入、删除、修改元素等,并提供了堆排序的实现过程。堆是一种特殊的树形数据结构,常用于优先队列的实现。通过down()和up()函数维护堆的性质,确保堆的正确性。堆排序是一种原地排序算法,其时间复杂度为O(n log n)。博客还展示了完整的C++代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

堆的两种核心操作
#include<iostream>

using namespace std;

const int N = 1e5 + 10;
int heap[N];
int len;


void down(int idx) {
    int t = idx;
    if (idx * 2 <= len && heap[idx * 2] < heap[t])t = idx * 2;
    if (idx * 2 + 1 <= len && heap[idx * 2 + 1] < heap[t])t = idx * 2 + 1;
    if (t != idx) {
        swap(heap[idx], heap[t]);
        down(t);
    }
}

void up(int idx) {
    while (idx / 2 && heap[idx] < heap[idx / 2]) {
        swap(heap[idx], heap[idx / 2]);
        idx /= 2;
    }
}

堆的基本操作
1.取出堆顶
heap[1]
2.删除堆顶元素
swap(heap[1],heap[size--]);
down(1);
3.堆中插入一个元素
heap[++size]=x;
up(size);
4.修改指定位置的值
heap[k]=x;
up(k),down(k);
5.删除指定位置的值
swap(heap[size--],heap[k]);
up(k),down(k);
堆排序
#include<iostream>

using namespace std;

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

void down(int idx) {
    int t = idx;
    if (idx *2<=len && heap[idx*2] < heap[t])t = idx*2;
    if (idx*2+1 <= len &&  heap[idx*2+1]<heap[t])t = idx *2+1;
    if (t != idx) {
        swap(heap[t], heap[idx]);
        down(t);
    }
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++)cin >> heap[i];
    len = n;
    //建立堆时间复杂度是O(n)
    for (int i = len/2; i; i--)down(i);
    while (n--) {
        cout << heap[1] << ' ';
        heap[1] = heap[len];
        len--;
        down(1);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值