堆排序

参考文章:堆排序原理及算法实现(最大堆)

堆排序代码
#include <iostream>
using namespace std;

void BigHeapAdjust(int32_t numList[], int32_t len, int32_t index){
    auto i = index;
    auto j = i * 2 + 1; //得到i的左孩子
    auto tmp = numList[i];

    while(j <= len) {
        if (j < len && numList[j] < numList[j+1]) {
            //右孩子比左孩子大,就直接取大的数比较
            j++;
        }

        //与index节点比较
        if (tmp < numList[j]) {
            numList[i] = numList[j];

            //继续监测子节点
            i = j;
            j = i * 2 + 1;
        }
        else {
            break;
        }
    }

    numList[i] = tmp;
}

void HeapSort(int32_t numList[], int32_t len) {
    auto index = len / 2 - 1; //最后一个非叶子节点
    for (; index >= 0; index--) {
        BigHeapAdjust(numList, len, index); 
    }

    for (index = len - 1; index > 0; index--) {
        auto tmp = numList[index];
        numList[index] = numList[0];
        numList[0] = tmp;

        BigHeapAdjust(numList, index - 1, 0); //从根节点开始判断
    }
}

void main() {
    int32_t numList[] = { 31, 41, 59, 26, 41, 58, 12 };
    int32_t count = sizeof(numList) / sizeof(numList[0]);
    HeapSort(numList, count);


    for (auto num : numList) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
}

返回排序算法分析总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值