自底向下构造堆算法的程序实现

       堆排序是一个非常有名的nlogn排序算法,而且是在位的(不需要额外的存储空间)。以前就在数据结构课程中学习过,并没有深入了解它。很汗颜今天我才第一次去实现这种算法,也这才感受到它的高效与优雅。贴出了完整代码,各位看官如果发现什么BUG或者有什么建议,欢迎提出。
1 #include <stdio.h>
2
3 #define HEAP_SIZE 10
4
5 void heap_bottom_up(int H[], int n);
6 bool delete_heap_root(int H[], int &n);
7 void print_heap(int H[], int n);
8
9 int main(int argc, char **argv)
10 {
11 int H[HEAP_SIZE+1]={0,3,11,6,2,4,8,99,76,84,7};
12 printf("initial array:\r\n");
13 print_heap(H,HEAP_SIZE);
14
15 //construct a heap
16 heap_bottom_up(H,HEAP_SIZE);
17 //heap sort by continually deleting the root
18 int i = HEAP_SIZE;
19 while( i > 1){
20 delete_heap_root(H,i);
21 }
22 printf("after heap sorted:\r\n");
23 print_heap(H,HEAP_SIZE);
24 return 0;
25 }
26 //delete the root of a heap and then make the rest a new heap
27 bool delete_heap_root(int H[], int &n){
28 //swap H[1](root) and H[n]
29 if( n == 0)
30 return false;
31 H[0] = H[1];
32 H[1] = H[n];
33 H[n] = H[0];
34 //now the heap size is n-1
35 n--;
36 //find an appropriate position for H[1]
37 bool is_heaped = false;
38 int k,v;
39 k=1;
40 v=H[1];
41 while(is_heaped == false && (k << 1) <= n){
42 int j = k << 1;
43 if(j < n && H[j] < H[j+1])
44 j++;
45 if(v > H[j]){
46 is_heaped = true;
47 }else{
48 H[k] = H[j];
49 k = j;
50 }
51 }//end of while
52 H[k] = v;
53 return true;
54 }
55 /**
56 * heap_bottom_up: construct a heap from a set of random element(int the form of array).
57 * @param H :initial set of elements that are to be heaped.
58 * note that we do not use H[0]. so the size of the array should be n+1
59 * @param n :size of the heap
60 * */
61 void heap_bottom_up(int H[], int n){
62 int i,v;
63 for( int i = n/2; i > 0; i--){
64 int k,v;
65 bool is_heaped = false;
66 k = i;
67 v = H[k];
68 while( is_heaped == false && (k << 1) <= n){
69 int j = k << 1;
70 if(j < n && H[j] < H[j+1])
71 j++;
72 if(v > H[j]){
73 is_heaped = true;
74 }else{
75 H[k] = H[j];
76 k = j;
77 }
78 }//end of while
79 H[k] = v; //Since the value of H[i] may be overwritten, you cannot use H[k] = H[i] here
80 }
81 }
82
83 void print_heap(int H[], int n){
84 for(int k = 1; k <= n; k++){
85 printf("%d ", H[k]);
86 }
87 printf("\r\n");
88 }

posted on 2011-04-27 15:29  Joshua Leung  阅读(573)  评论(0编辑  收藏  举报

导航