前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >堆排序

堆排序

作者头像
attack
发布2018-04-12 15:44:20
5970
发布2018-04-12 15:44:20
举报
代码语言:javascript
复制
 1 #include<iostream>
 2 using namespace std;
 3 int heap[101];
 4 int heap_size;
 5 void put(int d)                 //heap[1]为堆顶   插入 
 6 {
 7     int now, next;
 8     heap[++heap_size] = d;
 9     now = heap_size;
10     while(now > 1)
11     {
12         next = now/2;// 父节点 
13         if(heap[now] >= heap[next]) 
14         break;
15         swap(heap[now], heap[next]);
16         now = next;
17     }
18 }
19 int get()                //heap[1]为堆顶  获取 
20 {
21     int now=1, next, res= heap[1];
22     heap[1] = heap[heap_size--];//取出末尾元素 
23     while(now * 2 <= heap_size)
24     {
25         next = now * 2;// next 左孩子 
26         if (next < heap_size && heap[next + 1] < heap[next])
27         next++;
28         if (heap[now] <= heap[next]) 
29         break;
30         swap(heap[now], heap[next]);
31         now = next;
32     }
33     return res;
34 }
35 
36 int main()
37 {
38     int n;
39     cin>>n;
40     for(int i=1;i<=n;i++)
41     {
42         int dr;
43         cin>>dr;
44         put(dr);
45     }
46     for(int i=1;i<=n;i++)
47     {
48         cout<<get()<<endl;
49     }
50     return 0;
51 }

 stl

代码语言:javascript
复制
 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 using namespace std;
 5 int a[10000001];
 6 int main()
 7 {
 8     int n;
 9     cin>>n;
10     for(int i=1;i<=n;i++)
11     {
12         //cin>>a[i];
13         scanf("%d",&a[i]);
14     }
15     make_heap(a+1,a+n+1);
16     sort_heap(a+1,a+n+1);
17     for(int i=1;i<=n;i++)
18     {
19         //cout<<a[i]<<endl;
20         printf("%d\n",a[i]);
21     }
22     return 0;
23 } 
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-03-31 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档