博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2011-05-28 23:53  单鱼游弋  阅读(633)  评论(0编辑  收藏  举报
下面代码仅供本人复习数据结构所用,实用性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; 
}