堆排序

实现堆排序需要解决两个问题:

1、如何将n个待排序的数建成堆

2、输出堆顶元素之后。如何调整剩余n-1个元素,使其成为一个新堆

使用最大堆来进行堆排序算法实现,所谓堆排序就是每次交换堆顶元素与堆中最后一个元素,然后对前面的堆中的元素从堆顶开始调整。

具体代码如下:

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 
 6 
 7 void print(int a[],int n)
 8 {
 9     for(int j=0;j<n;j++)
10         cout<<a[j]<<" ";
11     cout<<endl;
12 }
13 
14 //调整堆过程
15 
16 void heapAdjust(int H[],int s,int length)
17 {
18     int tmp=H[s];
19 
20     int child=2*s+1;
21     while(child<length)
22     {
23         if(child+1<length&&H[child]<H[child+1])
24             ++child;
25 
26         if(H[s]<H[child])
27         {
28             H[s]=H[child];
29             s=child;
30             child=2*s+1;
31         }
32         else
33             break;
34         H[s]=tmp;
35     }
36     print(H,length);
37 }
38 //初始建堆过程
39 void buildingHeap(int H[],int length)
40 {
41     //从最后一个人有孩子的节点的位置i=(length-1)/2开始
42     for(int i=(length-1)/2;i>=0;--i)
43          heapAdjust(H,i,length);
44 }
45 //堆排序算法
46 void heapSort(int H[],int length)
47 {
48     buildingHeap(H,length);
49 
50     for(int i=length-1;i>0;i--)
51     {
52       //交换堆顶元素与对中的最后一个元素之后,对堆进行调整
53       int temp=H[i];
54       H[i]=H[0];H[0]=temp;
55       heapAdjust(H,0,i);
56     }
57 }
58 
59 int main()
60 {
61     int H[10]={3,1,5,7,2,4,9,6,10,8};
62     heapSort(H,10);
63 
64     cout<<"结果"<<endl;
65 
66     print(H,10);
67 }

 

posted @ 2016-01-20 17:10  尾巴草  阅读(158)  评论(0编辑  收藏  举报