Implementation of Heap Sort

本文提供了一个使用C++实现的堆排序算法示例。该算法通过构建最大堆并对堆顶元素与最后一个元素进行交换的方式来逐步将数组排序。文中详细展示了如何通过调整元素位置来维护堆的性质。

Follow is the C++ code of heap sort:

template<class T>
void _heap_sort(T * pUnsort, size_t len) { 
    for (int i = len; i >0; --i) {
        _make_heap(pUnsort, i);
        std::swap(pUnsort[0], pUnsort[i-1]);
    }
}

template<class T>
void _make_heap(T * pUnheap, size_t len) {
    int iMax;
    int iparent = len / 2 - 1;

    // first loop
    // to detect if the right child of i is exist.
    if ((iparent >= 0) && (2*iparent + 2 < len))
        iMax = (pUnheap[2*iparent + 1] > pUnheap[2*iparent + 2]) ? (2*iparent + 1) : (2*iparent + 2);    
    // only the left child of i is exist.
    else
        iMax = 2*iparent + 1;

    // swap two elements in first loop.
    if (pUnheap[iparent] < pUnheap[iMax])
            std::swap(pUnheap[iparent], pUnheap[iMax]);  

    for (int i = --iparent; i >= 0; -- i) { 
        iMax = (pUnheap[2*i + 1] > pUnheap[2*i + 2]) ? (2*i + 1) : (2*i + 2); 
        if (pUnheap[i] < pUnheap[iMax])
            std::swap(pUnheap[i], pUnheap[iMax]);
    }
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值