.6 有关大根堆的push pop操作

 

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 #define  MAX_HEAP 200
 4 #define heap_full(n) (n==MAX_HEAP)
 5 #define heap_empty(n) (!n)
 6 //最大堆(大根堆)插入操作 删除操作
 7 
 8 
 9 typedef struct{
10     int k;
11     }element ;
12 element heap[MAX_HEAP];
13 
14 void push(element item, int * n)
15 {
16     int i ;
17     if(heap_full(*n)){
18         fprintf(stderr, "the heap is full\n");
19         exit(EXIT_FAILURE);
20     }
21     i = ++(*n);
22     while( i != 1 && item.k>heap[i/2].k){
23         heap[i] = heap[i/2];
24         i = i/2;
25     }
26     heap[i] = item;
27 }
28 
29 element pop(int * n )
30 {
31     int par , chi ,i;
32     element item , tmp ;
33     if(heap_empty(*n)){
34         fprintf(stderr, "the heap is empty\n");
35         exit(EXIT_FAILURE);
36     }
37     item = heap[1];
38     tmp = heap[(*n)--];
39     par = 1 ; chi = 2 ;
40     while( chi <= *n){
41         if( chi<*n && heap[chi].k < heap[chi+1].k){
42             chi++;
43         }
44         if( tmp.k >= heap[chi].k) break;
45         heap[par] = heap[chi] ;
46         par = chi ; chi *= 2;
47     }
48     heap[par] = tmp ;
49     return item  ;
50 }
51 
52 int main()
53 {
54     int arr[] = {1,5,3,2,90,6} ;
55     int n = 0 , i , b1 ;
56     element item ;
57     b1 = sizeof(arr) / sizeof(int) ;
58     for(i = 0 ; i < b1 ; i++){
59         item.k = arr[i] ;
60         push(item , &n) ;
61     }
62 
63     while(n>0){
64         item = pop(&n) ;
65         printf("%d %d\n",b1-n , item.k);
66     }
67     return 0 ;
68 }

 

posted @ 2013-12-23 22:08  shaughn  阅读(445)  评论(0编辑  收藏  举报