堆排序

View Code
 1 #include <stdio.h>   
 2 #include <stdlib.h>   
 3 #define MAXLEN 10  
 4 #define K 3   
 5 
 6 
 7 void HeapAdjust(int array[], int i, int len)  
 8 {  
 9     int temp=array[i];
10     int j;
11     for (j=2*i; j<len; j*=2)
12     {
13         if (j<len && array[j] < array[j+1])
14         {
15             ++j;
16         }
17         if (temp < array[j])
18         {
19             array[i]=array[j];
20             i=j;
21         }
22         else
23             break;
24     }
25     array[i]=temp;
26    
27 }  
28 
29 void Swap(int& a,int& b)  
30 {  
31     int temp;
32     temp=a;
33     a=b;
34     b=temp;
35 }  
36 
37  
38 void HeapSort(int array[], int len)
39 {
40     int i;
41     for (i=len/2-1; i>=0; --i)
42     {
43         HeapAdjust(array, i, len);
44     }
45     for (i=len-1; i>=1; --i)
46     {
47         Swap(array[0], array[i]);
48         HeapAdjust(array,0,i-1);
49     }
50 }
51 
52 int main()  
53 {  
54     int array[MAXLEN];  
55     int i;
56     for(i=0;i<MAXLEN;++i)  
57         array[i] =MAXLEN-i;  
58     HeapSort(array,MAXLEN);
59     for (i=0; i<MAXLEN; i++)
60     {        
61         printf("%d ", array[i]);
62     }
63     return 0;  
64 }  

 

posted @ 2012-05-10 18:25  徐露  阅读(170)  评论(0编辑  收藏  举报