HeapSort

在O(nlgn)的複雜度下可以實現排序,
# include <stdio.h>
# define HEAP_SIZE    7

int Heap_Size = HEAP_SIZE - 1 ;
int Parent(int i){

	return i/2;
}

int Left(int i){

	return 2*i;
}

int Right(int i ){

	return 2*i+1;
}

void Exchange(int *p , int * q){
	int temp = * p ; 
	*p = * q; 
	*q = temp ;
}

void Max_Heapfy(int A[], int i){
	int left = Left(i);
	int right= Right(i);
	int maxer ;

	if( left <= Heap_Size && A[i] < A[left]){
		maxer = left;
	}else{
		maxer = i;
	}
	if (right <= Heap_Size &&  A[maxer] < A[right] ){
		maxer = right;
	}

	if (i != maxer){
		Exchange(&A[maxer],&A[i]);
		Max_Heapfy(A,maxer);
	}

	return ;
}

void Build_Max_Heap(int A[]){
	for (int i = Heap_Size/2 ; i >= 0 ; i --){
		Max_Heapfy(A,i);
	}
}

void HeapSort(int A[]){
	Build_Max_Heap(A);
	for (int i = Heap_Size ; i >= 1 ;i --){
		Exchange(&A[0],&A[i]);
		Heap_Size = Heap_Size - 1;
		Max_Heapfy(A,0);
	}
}

int main(void){
	int a[] = { 7,1,3,2,4,6,5};
	HeapSort(a);
	for (int i = 0 ; i < HEAP_SIZE ; i ++ ){
		printf("%5d  ", a[i]);
	}
	
	return 0;
}


發佈了14 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章