本文介绍了为什么这个heapsort不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

struct node{
	int item;
};
int N;

void Max_Heapify( struct node StrArr[] , int i ) {
	//printf("i=%d\n",i);
	int LC=2*i;
	int RC=(2*i)+1;
	int Largest;
	//printf("Values i %d,LC %d, Rc %d,");

	if( LC<=N && StrArr[LC].item > StrArr[i].item ) {

		Largest=LC;

	}

	if( RC<=N && StrArr[RC].item > StrArr[LC].item ) {

		Largest = RC;

	}
	//printf("Largest %d\n\n");

	if( Largest != i ){

		int temp = 	StrArr[Largest].item ;
		StrArr[Largest].item = StrArr[i].item ;
		StrArr[i].item = temp ;

		Max_Heapify(StrArr, Largest) ;
	}

}

void Build_Max_Heap( struct node StrArr[] ) {

	int i;
	for( i=N/2 ; i >= 1 ; i-- ){
		//printf("Call %d:\n",i);
		Max_Heapify( StrArr , i);
	}

}

void HeapSort( struct node StrArr[] ) {

	 	Build_Max_Heap(StrArr);

		while(N>=1) {

			int temp = 	StrArr[1].item ;
			StrArr[1].item = StrArr[N].item ;
			StrArr[N].item = temp ;

			printf("%d ",StrArr[N].item);

			Max_Heapify( StrArr , 1);
			N=N-1;

		}
}

main() {

	printf("Enter size of the Array:");
	scanf("%d",&N);
	struct node StrArr[N];
	int i;
	printf("\nEnter Elements of the Array- ");
	for( i = 1 ; i <= N ; i++ ) {
		scanf("%d",&StrArr[i].item);
	}
	/*for( i = 1 ; i <= N ; i++ ) {
		printf("%d",StrArr[i].item);
	}*/
	printf("\nArray After HeapSort:");
	HeapSort(StrArr);

}





我的尝试:



当我尝试时,存储在LC和RC中的值不正确...!



What I have tried:

When I tried it,the Value stored in LC and RC are not correct...!

推荐答案



这篇关于为什么这个heapsort不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 01:52