Introduce to algorithm--------pseudo code to C/C++ code(Chapter 6)
来源:互联网 发布:js检验 编辑:程序博客网 时间:2024/05/16 11:50
堆排序:
如果只是从字面意思出发,大家很难理解堆排序的原理,但如果说的详细一点,‘堆排序’中的‘堆’实际上指的是二叉堆,
那么,也许堆排序不那么难记了。简单的说堆排序是以二叉堆为基础,多次对数组build二叉堆,从而进行排序的一种algorithm。
先给出build二叉堆的code:
//size if the size of arraytemplate <typename T>void max_heapify (T* A, int i, int size){//get left and right child's indexint l = 2 * i + 1,r = l + 1;int largest;if (l < size && A[l] > A[i])largest = l;else largest = i;if (r < size && A[r] > A[largest])largest = r;if (largest != i){T temp = A[i];A[i] = A[largest];A[largest] = temp;max_heapify<T> (A, largest, size);}}template <typename T>void build_max_heap (T* A, int length){for (int i = length / 2 - 1; i >= 0; --i)max_heapify<T> (A, i, length);}build二叉堆的函数是build_max_heap,这里实现为一个模板,该函数简单的调用max_heapify函数,至于为什么从数组下标length / 2 - 1处开始进行调用,
请参见算法导论。
有了二叉堆的build算法,堆排序就简单明了了。以最大堆为例, 堆排序是先对整个数组进行最大堆的构建,然后将根节点(即最大值)与数组末尾值进行
调换。接着将数组末尾值排除在外,以剩余数组为整体重复上述过程,直到剩余数组为零。
下面是堆排序代码(也以模板给出):
template <typename T>void heap_sort (T* A, int length){build_max_heap<int> (A, length);for (int i = length - 1; i > 0; --i){Ttemp = A[0];A[0] = A[i];A[i] = temp;max_heapify<int> (A, 0, i);}}
以上代码仅经过一组数据测试,不完善之处敬请指正!
For more detail information, see introduce to algorithm.
0 0
- Introduce to algorithm--------pseudo code to C/C++ code(Chapter 6)
- Introduce to algorithm-------pseudo code to C/C++ code(Chapter 2)
- Introduce to Algorithm--------pseudo code to C/C++ code(Chapter 4)
- Introduce to algorithm--------pseudo code to C/C++ code(Chapter 7)
- Introduce to algorithm--------pseudo code to C/C++ code(Chapter 8)
- Introduce to algorithm-----pseudo code to C/C++ code (chapter 11)
- Introduce to algorithm--------pseudo code to C/C++ code(chapter 12)
- Introduce to algorithm--------pseudo code to C/C++ code(chapter 13)
- Introduce to algorithm--------pseudo code to C/C++ code(chapter 15)
- Introduce to algorithm--------pseudo code to C/C++ code (chapter 16)
- Introduce to algorithm--------pseudo code to C/C++ code (chapter 18)
- Introduce to algorithm--------pseudo code to C/C++ code (chapter 23)
- Introduce to algorithm--------pseudo code to C/C++ code (chapter 24)
- C code to implement RSA Algorithm(Encryption and Decryption)
- How to study C && ASM Code(6)
- Pre-IPL RAM Stage pseudo C code
- Introduction to Algorithm(chapter 6)
- How to study C && ASM Code(1)
- PRML-系列一之1.2.1
- HTTPS是如何保证连接安全
- 发布不显示jqueryUi控件
- dfs 求全排列
- C#文件读写操作实例
- Introduce to algorithm--------pseudo code to C/C++ code(Chapter 6)
- 面向对象(3)
- css 通用样式头(个人专用)
- JS判断系统
- JS获取URL参数
- 未能从程序集“Oracle.ManagedDataAccess, Version=4.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342
- JavaScript 注入攻击
- ①算法之队列解QQ密码
- Windows Serial Port Programming in C.