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

堆排序

时间:2015-07-20 22:52:11      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

 1 #include<iostream>
 2 using namespace std;
 3 
 4 struct sqlist
 5 {
 6     int length;//待排序数组的长度
 7     int ary[100];//待排序数组(从下表号1开始)
 8 }
 9 
10 //对于L【s-m】,假设除s点外,其它的都是堆排序好了的
11 //开始进行堆调整,使得所有的满足堆的顺序。
12 //对于s它的左右子树的坐标为2*s和2*s+1,若是s处的值为这三者中最大的那么直接可以终止了
13 //若是不是,则将s处的值进行交换,将改变最大值又开始找它的左右子树重复上面得分过程。
14 void heapsort(sqlist* L,int s,int m)
15 {
16     int temp,j;
17     temp=L->ary[s];
18     for(j=2*s;j<m;j*=2)
19     {
20         if(j<m&&L->ary[j]<L->ary[j+1])
21             j++;
22         if(temp>L->ary[j])
23             break;
24         L->ary[s]=L->ary[j];
25         s=j;
26     }
27     L->ary[s]=temp;
28 }
29 
30 //将数组中坐标为i和j的数进行交换
31 void swapd(sqlist* L,int i,int j)
32 {
33     int temp;
34     temp=L->ary[i];
35     L->ary[i]=L->ary[j];
36     L->ary[j]=temp;
37 }
38 
39 //堆排序的主程序
40 void duipaixu(sqlist* L)
41 {
42     //这里为什么是length/2是因为完全二叉树的性质,从这里正好最后一个非叶子节点开始往前调整
43     //使的其为堆结构
44     for(int i=L->length/2;i>0;i--)
45         heapsort(L,i,L->length);
46     //从后往前,将第一个(堆顶最大值)与第i个数交换。再对1到i-1进行堆调整,使得其为堆结构。
47     for(int i=L->length;i>1;i--)
48     {
49         swapd(L,i,1);
50         heapsort(L,1,i-1);
51     }
52     
53 }
54 
55 int main()
56 {
57 
58 }

 

堆排序

标签:

原文地址:http://www.cnblogs.com/yanliang12138/p/4662735.html

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