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


    下面代码仅供本人复习数据结构所用,实用性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; 
    }
    
  • 相关阅读:
    分享:CodeLite 5.1 发布,C++ 集成开发环境
    Elementary Sockets:readn, writen, and readline Functions
    How to handle boost::iostreams::gzip_dec C++ Forum
    分享:python/c++ 深拷贝与浅拷贝(转)写∽好
    我刚刚通过 @盛大网盘EverBox 分享了 Web协议与实践HTTP.、网络协议、缓存技术和....pdf, 欢迎大家下载!
    Is zlib threadsafe?
    print "\v"
    分享:混合编译c和cpp的makefile模板
    Elementary Sockets:readn, writen, and readline Functions
    c的socket教程 二进制 博客频道 CSDN.NET
  • 原文地址:https://www.cnblogs.com/wxxweb/p/2061432.html
Copyright © 2020-2023  润新知