您的位置:首页 > 编程语言 > C语言/C++

堆排序(C++模版技术实现)

2011-05-28 23:53 435 查看
下面代码仅供本人复习数据结构所用,实用性N低,各位飘过吧~~哈哈:>

//
// C++ 模版技术实现堆排序.
//

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <stdexcept>

//
// 堆化函数模版.
// 当一棵二叉树除了根节点外,其子树都满足堆性质时,
// 对根节点进行调整,使得整棵二叉树树都满足堆性质.
//
template <typename T>
void heapify(T *array, size_t low, const size_t high)
{
T temp = array[low];
for (size_t large = 2 * low; large <= high; low = large, large *= 2)
{
if (large < high && array[large] < array[large + 1]) {
large++;
}
if (temp >= array[large]) {
break;
}
array[low] = array[large];
}
array[low] = temp;
}

//
// 构建堆函数模版.
// 从最底层最小子树开始逐层向上扩大进行堆化.
//
template <typename T>
void buildHeap(T *array, const size_t count)
{
for (size_t i = count / 2; i > 0; --i)
{
heapify(array, i, count);
}
}

//
// 堆排序函数模版.
//
template <typename T>
void heapSort(T *array, const size_t first, const size_t last)
{
if (NULL == array || first >= last) {
throw std::invalid_argument("堆排序函数实参错误.");
}

//
// 二叉树节点以顺序结构存储,即存储在数组中.
// 为了满足二叉树性质,即根节点索引值为 1,
// 需要对于由索引 first 到 last 指定的连续数据元素进行索引值映射,
// 使起始元素索引从 1 开始. 即二叉树顺序存储在数组 A[1..n] 中.
//
T *pBinTree = array + first - 1;
const size_t n = last - first + 1;

T temp;
buildHeap(pBinTree, n);
for (size_t i = n; i > 1; --i)
{
temp = pBinTree[1];
pBinTree[1] = pBinTree[i];
pBinTree[i] = temp;
heapify(pBinTree, 1, i - 1);
}
}

//
// 测试.
//
int main(void)
{
char szTest[] = "Heap sort algorithm test case !";
int iarrTest[] = {23, 12, 2, 123, 72, 35, 49, 51, 83, 94, 65};
const size_t INT_ARR_SIZE = sizeof(iarrTest) / sizeof(iarrTest[0]);

heapSort(szTest, 0, strlen(szTest) - 1);
heapSort(iarrTest, 0, INT_ARR_SIZE - 1);

std::cout << szTest << std::endl;

for (size_t i = 0; i < INT_ARR_SIZE; ++i)
{
std::cout << iarrTest[i] << " ";
}
std::cout << std::endl;

return EXIT_SUCCESS;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: