堆排序
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了堆排序,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1745字,纯文字阅读大概需要3分钟。
内容图文
![堆排序](/upload/InfoBanner/zyjiaocheng/1054/06b437b2c4f94c2b9ef027df222dcc8b.jpg)
堆排序
堆排序以二叉形式。
以数组形式表示。a[1] 是二叉堆的跟结点,每个结点的有左右子结点。规定每个结点的值大于其子节点的堆叫最大堆,小于的叫最小堆。
无序数组通过建堆的方式建立成一个最大或最小堆。
算了 ,说不清,上代码。
代码:
#include <bits/stdc++.h> using namespace std; const int MAXN = 100; int a[MAXN] = {0,4,1,3,2,16,9,10,14,8,7};//10 int n = 10;//数的个数 void Max_Heap(int x,int n) { //维护根节点为x的最大堆 //n为数组长度 int pos = x; int left_pos = x<<1; int right_pos = (x<<1) + 1; if (left_pos <= n && a[pos] < a[left_pos]) pos = left_pos; if (right_pos <= n && a[pos] < a[right_pos]) pos = right_pos; if (pos != x) { int tmp = a[pos]; a[pos] = a[x]; a[x] = tmp; Max_Heap(pos,n); } return ; } void Min_Heap(int x,int n) { //维护根节点为x的最小堆 //n为数组长度 int pos = x; int left_pos = x<<1; int right_pos = (x<<1) + 1; if (left_pos <= n && a[pos] > a[left_pos]) pos = left_pos; if (right_pos <= n && a[pos] > a[right_pos]) pos = right_pos; if (pos != x) { int tmp = a[pos]; a[pos] = a[x]; a[x] = tmp; Min_Heap(pos,n); } return ; } void Build_Max_Heap(int x,int n) { //给数组1-x位置建立最大堆,1为根节点 //n为数组长度 for (int i = x/2;i > 0;i--) Max_Heap(i,n); } void Build_Min_Heap(int x,int n) { //给数组1-x位置建立最小堆,1为根节点 //n为数组长度 for (int i = x/2;i > 0;i--) Min_Heap(i,n); } void Print_Max_Heap(int x) { //输出最大堆 while (x) { cout << a[1] << ‘ ‘; int tmp = a[x]; a[x] = a[1]; a[1] = tmp; Max_Heap(1,x-1);//最后一个结点不使用,所以维护长度减1 x--; } } void Print_Min_Heap(int x) { //输出最小堆 while (x) { cout << a[1] << ‘ ‘; int tmp = a[x]; a[x] = a[1]; a[1] = tmp; Min_Heap(1,x-1); x--; } } int main() { Build_Max_Heap(n,n); Print_Max_Heap(n); Build_Min_Heap(n,n); Print_Min_Heap(n); return 0; } //运行结果 //16 14 10 9 8 7 4 3 2 1 //1 2 3 4 7 8 9 10 14 16
原文:https://www.cnblogs.com/YDDDD/p/10293826.html
内容总结
以上是互联网集市为您收集整理的堆排序全部内容,希望文章能够帮你解决堆排序所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。