堆排序

#include <stdio.h>
#include <stdlib.h>

//int a[]={1000,10000,9,10,30,999999,50,23,90,100,10};
int a[]={10,9,8,7,6,5};

int length=sizeof(a)/sizeof(int);

int swap(int start, int stop){
	int temp;
	temp=a[start];
	a[start]=a[stop];
	a[stop]=temp;
	return 0;	
}


int buildsubheap( int k , int length1 ){
	
	int biggerpos;	
	if( (2*k+1) > (length1 -1) ){
		return 0;
	}
	biggerpos=2*k+1;
	if((2*k+2)<=(length1-1)){
		biggerpos=a[2*k+2]>a[2*k+1]?(2*k+2):(2*k+1);
	}

	if(a[biggerpos] >a[k]){
		swap(biggerpos,k);
	}
	buildsubheap(biggerpos , length1);

}

int buildbottomtotop(){
	
	int k=length-1;
	int biggerpos;
	int i;
	int outer=k;

	if(length <=1){
		return 0;
	}

	
		while (k>0){
			printf("\n k=%d \n", k);
			biggerpos=k;
			if( (k%2)==0 ){
				biggerpos=a[k]>a[k-1]?k:(k-1);
			}

			if( a[biggerpos] > a[(k-1)/2] ) {
				swap( biggerpos,((k-1)/2) );
				buildsubheap(biggerpos, length);
			}		
			k--;
		}
		for(i=0;i<=length-1;i++){
			printf("%d,", a[i]);
		}
		printf("\n outer=%d \n", outer);
		while( outer >0 ){
			swap(outer, 0);
			buildsubheap(0 , outer);
			outer--;
		}
	}	
		







int main(){
	
	printf("length= %d\n",length);	
	int i;
	printf("\n");
	//quicksort(0,length-1);
	buildbottomtotop();
	printf("\n\n\n");
	for(i=0;i<length;i++){
		printf("%d\n" , a[i]);
	}
	printf("\n");
	
	return 0;
}		

自己实现的堆排序就是好  

posted @ 2017-01-19 00:34  友哥  阅读(151)  评论(0编辑  收藏  举报