码迷,mamicode.com
首页 > 其他好文 > 详细

swust oj 1015

时间:2019-04-08 21:25:30      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:styles   algorithm   数据   ret   stream   编写   ant   程序   info   

堆排序算法

1000(ms)
10000(kb)
2631 / 5595

编写程序堆排序算法。按照从小到大的顺序进行排序,测试数据为整数。

输入

第一行是待排序数据元素的个数; 第二行是待排序的数据元素。(提示:用小根堆)

输出

一趟堆排序的结果。

样例输入

10
50 36 41 19 23 4 20 18 12 22

样例输出

4 12 20 18 22 41 50 36 19 23

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<string>
 5 #include<cstdio>
 6 using namespace std;
 7 
 8 void sift(int arr[],int low,int high)
 9 {
10     int i=low,j=2*i;
11     int tmp=arr[i];
12     while(j<=high)
13     {
14         if(j<high&&arr[j]>arr[j+1])  //小的上浮,大的下沉
15             j++;
16         if(tmp>arr[j])
17         {
18             arr[i]=arr[j];
19             i=j;
20             j=2*i;
21         }
22         else
23             break;
24     }
25     arr[i]=tmp;
26 }
27 
28 void Heapsort(int arr[],int n)
29 {
30     for(int i=n/2;i>=1;i--)  //建立初始堆,第一趟
31         sift(arr,i,n);
32 }
33 
34 int main()
35 {
36     int n;
37     int arr[1000];
38     cin>>n;
39     for(int i=1;i<=n;i++)
40         cin>>arr[i];
41     Heapsort(arr,n);
42     for(int i=1;i<=n;i++)
43         cout<<arr[i]<<" ";
44     return 0;
45 }

 

 

swust oj 1015

标签:styles   algorithm   数据   ret   stream   编写   ant   程序   info   

原文地址:https://www.cnblogs.com/Iwpml-595/p/10673232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!