关于堆排序
最近在学习堆排序,安装堆排序的思路自己写了个程序,但是发现存在一点问题。按照堆排序的思想,建完大顶堆后,根节点与最后一个叶子节点交换,然后剩下的重新建堆。但是按照我下面的程序,并不能建成一个堆,也就是说最后一次交换是发生在根节点和第一层节点之间,但是根节点有可能小于第三层节点中的数,交换之后就违背了堆的定义(根节点大于或小于子结点),因此说不能建成堆。但是最终排序的结果确实对的,而且还省去了一次比较,应该是程序的效率更高才是。不知道程序这样写对不对?
1 #include "stdafx.h"
2
3 #include <iostream>
4
5 using namespace std;
6
7 void HeapCreate(int* source, int n)
8 {
9 int start;
10 int temp;
11 for(start=n/2;start>0;start--)
12 {
13 temp = source[start-1];
14 if(2*start+1<=n)
15 {
16 if (source[start-1]<source[2*start-1]||source[start-1]<source[2*start+1-1])
17 {
18 if(source[2*start-1]>=source[2*start+1-1])
19 {
20 source[start-1] = source[2*start-1];
21 source[2*start-1] = temp;
22 }
23 else
24 {
25 source[start-1] = source[2*start+1-1];
26 source[2*start+1-1] = temp;
27 }
28 }
29 }
30 else
31 {
32 if(source[start-1]<source[2*start-1])
33 {
34 source[start-1] = source[2*start-1];
35 source[2*start-1] = temp;
36 }
37
38 }
39
40 }
44 }
45
46 void HeapSort(int* heap, int m)
47 {
48 int r;
49 int endnum = m;
50 while(m>1)
51 {
52 HeapCreate(heap,m);
53 for(int i=0;i<endnum;i++)
54 cout<<heap[i]<<" ";
55 cout<<endl;
56 r = heap[0];
57 heap[0] = heap[m-1];
58 heap[m-1] = r;
59 m--;
60 } ;
61 for(int i=0;i<endnum;i++)
62 cout<<heap[i]<<" ";
63 cout<<endl;
64
65 }
66
67 int _tmain(int argc, _TCHAR* argv[])
68 {
69 int num[]={10,22,4,8,13,6,0,3,31,6,12,17};
70 HeapSort(num,12);
71 system("pause");
72 return 0;
73 }

浙公网安备 33010602011771号