堆排序(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; } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· NetPad:一个.NET开源、跨平台的C#编辑器
· PowerShell开发游戏 · 打蜜蜂