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]);
}
}

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

被折叠的 条评论
为什么被折叠?



