码迷,mamicode.com
首页 > 编程语言 > 详细

1)②排序算法之选择排序[2]堆排序

时间:2015-12-04 12:38:37      阅读:235      评论:0      收藏:0      [点我收藏+]

标签:

 1 #include "iostream"
 2 #include "iomanip"
 3 #include "time.h"
 4 using namespace std;
 5 
 6 #define num 28
 7 typedef int type;//type类型为int
 8 
 9 /*
10 *调整数组A中以K为根的子序列为堆,其中最大的元素下标为m
11 *假设以2k,2k+1为根的左右子树均是堆
12 */
13 void sift(type Array[],int k,int m)
14 {
15     int i,j,x;
16     bool finished = false;
17 
18     x =Array[k];//临时保存当前根植
19     i = k;//指示空位
20     j = 2*i;//j先指向其左孩子结点
21     while(j<=m &&!finished)//确定i结点不是叶子节点且搜索未结束
22     {
23         if((j<m)&&(Array[j]<Array[j+1]))j++;//让j指向左右孩子中的最大者
24         if(x>=Array[j])finished = true;//若原根最大,置搜索和帅选结束标志
25         else{
26             Array[i] = Array[j];//大的孩子结点值上移
27             i = j;//继续往下帅选:i指示新的空位,j相应改变
28             j*=2;
29         }
30     }
31     Array[i] = x;//将原根值填充到所搜索到的当前的空位置中
32 }
33 
34 /*
35 *对数组Array中下标为1~n的元素用堆排序算法实现排序
36 */
37 void Heap_Sort(type Array[],int n)
38 {
39     int i;
40     time_t start,end;
41     start = clock();
42     for(i=n/2;i>=1;i--)
43     {
44         sift(Array,i,n);//建初始堆
45     }
46     for(i=n;i>=2;i--)//控制排序过程
47     {
48         type temp;
49         temp = Array[1];
50         Array[1] = Array[i];
51         Array[i] = temp;
52         sift(Array,1,i-1);//调整子序列Array[1]~Array[i-1]为堆
53     }
54     end = clock();
55     cout<<"The Merge_Sorted Array:"<<endl;
56     for(i=1;i<=n;i++)
57     {
58         cout<<setw(5)<<Array[i]<<" ";
59         if(i%10==0)cout<<endl;
60     }
61     cout<<endl;
62 
63     cout<<"performnace time:";
64     cout<<(double)(end - start )/1000<<"Seconds"<<endl;
65 }
66 int main()
67 {
68     type Array[num+1];
69     int i;
70     cout<<"Initialize Array:"<<endl;
71     for(i=1;i<=num;i++)
72     {
73         Array[i] = rand()%1000;
74         cout<<setw(5)<<Array[i]<<" ";
75         if(i%10==0)cout<<endl;
76     }
77     cout<<endl;
78     Heap_Sort(Array,num);
79     return 0;
80 }

技术分享

1)②排序算法之选择排序[2]堆排序

标签:

原文地址:http://www.cnblogs.com/minmsy/p/5018918.html

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