O(nLogn)排序 :堆

本文详细介绍了一种基于堆的排序算法实现过程,包括调整堆、构建最大堆和堆排序的完整步骤。通过C++代码示例,展示了如何使用vector容器和算法库函数来实现堆排序,适用于需要高效排序的数据结构场景。

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

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


void adjust_up(vector<int> &v, int index)
{
    int parent = 0;
    int hole = index;
    int temp = v.at(index);
    for(; (hole - 1) / 2 >= 0 && hole > 0; hole = parent)
    {
        parent = (hole - 1) / 2;
        if (temp > v.at(parent))
        {
            v.at(hole) = v.at(parent);
        }
        else
        {
            break;
        }
    }
    v.at(hole) = temp;
}


void adjust_down(vector<int> &v, int index, int length)
{
    int child = 0;
    int hole = index;
    int temp = v.at(index);
    for(; hole * 2 + 1 <= length; hole = child)
    {
        child = hole * 2 + 1;
        if((child + 1 <= length) && (v.at(child  + 1) > v.at(child)))
        {
            ++child;
        }
        if(v.at(child) > temp)
        {
            v.at(hole) = v.at(child);
        }
        else
        {
            break;
        }
    }
    v.at(hole) = temp;
}


void build_heap(vector<int> &v, int length)
{

    for (int i = (v.size() - 2) / 2; i >= 0; i--)
    {
        adjust_down(v, i, length);
    }
}

int main(int argc, const char **argv)
{
    auto put = [](vector<int > &v)
    {
        cout << "---" << endl;
        for (auto &n : v)
        {
            cout << n << endl;
        }
    };

    vector<int> v {23, 45, 3, 56, -3, 11};

    for(int i = v.size() - 1; i > 0; i--)
    {
        build_heap(v, i);
        std::swap(v.at(0), v.at(i));
    }

    put(v);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

少言才不会咸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值