标签:style blog io color sp for div log bs
1 #include<stdio.h> 2 int h[101]; 3 int n; 4 void swap(int x,int y)//交换 5 { 6 int t=h[x]; 7 h[x]=h[y]; 8 h[y]=t; 9 } 10 void siftdown(int i)//调整一次 11 { 12 int t,flag=0; 13 while(2*i<=n&&flag==0){ 14 if(h[i]<h[i*2]) 15 t=2*i; 16 else 17 t=i; 18 if(i*2+1<=n) 19 if(h[i]<h[2*i+1]) 20 t=2*i+1; 21 if(t!=i) 22 { 23 swap(t,i); 24 i=t; 25 } 26 else 27 flag=1; 28 } 29 } 30 void creat()//建堆 31 { 32 int i; 33 for(i=n/2;i>=1;i--) 34 { 35 siftdown(i); 36 } 37 } 38 void heapsort()//堆排序 39 { 40 while(n>1) 41 { 42 swap(1,n); 43 n--; 44 siftdown(1); 45 } 46 } 47 int main() 48 { 49 int i,num; 50 scanf("%d",&num); 51 for(i=1;i<=num;i++) 52 scanf("%d",&h[i]); 53 n=num; 54 creat(); 55 heapsort(); 56 for(i=1;i<=num;i++) 57 printf("%d ",h[i]); 58 printf("\n"); 59 return 0; 60 }
标签:style blog io color sp for div log bs
原文地址:http://www.cnblogs.com/yanglingwell/p/4118395.html