堆排序算法C++代码讲解

版权声明:如果转载,请注明出处。 https://blog.csdn.net/S_999999/article/details/82832620
// 堆排序,C++递归和非递归写法 
/*
测试数据: 
14
99 5 36 7 22 17 46 12 2 19 25 28 1 92
*/
#include<iostream>
using namespace std;
int h[1000],n;
void swap( int x,int y){
     int tmp = h[x];
     h[x] = h[y]; 
     h[y] = tmp;
} 
// 递归写法 
void siftdown( int i ){
	 
	int t = i;
	if( i *2<=n && h[t] > h[i*2])
	       t = i*2;
	if( i*2+1<=n&&h[t] > h[i*2+1])
	       t =i*2+1;
    if( i!=t){
    	swap(i,t);
    	siftdown(t);
	}		          
}
//非递归写法
/*
void siftdown( int i ){
      int t ,flag=0;
	  while( i*2<=n&&flag==0){
	  	 if( h[i] > h[i*2] )
	  	      t = i*2;
	  	 else t = i; 
	  	
		 if( i*2+1<=n ) 
	  	    if( h[t] > h[i*2+1] )
	  	         t = i*2+1;
	     if( i!=t){
		 	swap(i,t);
		 	i=t;
		  }	    
		 else flag = 1;   
	  }	 
} 
*/
void heapsort( ){
	
	//先创建堆
	for( int i=n/2;i>=1;i--)
	    siftdown(i);
    while( n > 1 ){
    	swap(1,n);
    	n--;
    	siftdown(1);// 记住,每查找完一次,就要重新排序 
	}		 
}
int main(void){
	
	 int i,num;
	scanf("%d",&num);
	n =num;
	for( int i=1;i<=num;i++)
	 scanf("%d",&h[i]);
	 
	 heapsort();
	for( int i=num;i>=1;i--)
	   printf("%d ",h[i]);
	return 0;
	
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/S_999999/article/details/82832620