数据结构与算法 ~ 排序 ~ 堆排序

数据结构与算法 ~ 排序 ~ 堆排序

/*sort--heapsort*/
#include<stdlib.h>
#include<stdio.h>
#define MAX 100

int create_heap(int *heap){
	int e,length=0;
	printf("\n=======创建=======\n");
	printf("\n请输入数字(退出输入0):");
	scanf("%d",&e);
	while(e!=0){
		heap[++length]=e;
		printf("\n请输入数字(退出输入0):");
		scanf("%d",&e);
	}/*while*/
	return length;
}/*create_heap*/

void Print(int *heap,int length,int n){
	int i;
	printf("\n==当前堆排序结果:==:");
	for (i=1;i<=length;++i){
		if (i==n)  printf("=||=,");
		printf("%d,",heap[i]);
	}
}

void heapadjust(int *heap,int s,int m){
	int j;
	heap[0]=heap[s];
	for(j=2*s;j<=m;j*=2){
		if (j<m && heap[j]<heap[j+1]) 
			++j;
		if (heap[0]>heap[j]) 
			break;
		heap[s]=heap[j];
		s=j;
	}/*for*/
	heap[s]=heap[0];
}/*heapadjust*/

void heapsort(int *heap,int length){
	int i;
	for (i=length/2;i>0;--i)
		heapadjust(heap,i,length);
	Print(heap,length,0);
	for(i=length;i>1;--i){
		heap[0]=heap[1];
		heap[1]=heap[i];
		heap[i]=heap[0];
		heapadjust(heap,1,i-1);
		Print(heap,length,i);
	}/*for*/
}

main(){
 int length,heap[MAX];
 length=create_heap(heap);
 Print(heap,length,length+1);
 printf("\n堆的长度是%d",length);
 printf("\n=======over============\n");
 heapsort(heap,length);
 Print(heap,length,0);
 system("pause");
 exit(0);
}

运行结果是:


=======创建=======

请输入数字(退出输入0):59

请输入数字(退出输入0):48

请输入数字(退出输入0):75

请输入数字(退出输入0):96

请输入数字(退出输入0):86

请输入数字(退出输入0):23

请输入数字(退出输入0):37

请输入数字(退出输入0):59

请输入数字(退出输入0):65

请输入数字(退出输入0):14

请输入数字(退出输入0):0

==当前堆排序结果:==:59,48,75,96,86,23,37,59,65,14,
堆的长度是10
=======over============

==当前堆排序结果:==:96,86,75,65,59,23,37,59,48,14,
==当前堆排序结果:==:86,65,75,59,59,23,37,14,48,=||=,96,
==当前堆排序结果:==:75,65,48,59,59,23,37,14,=||=,86,96,
==当前堆排序结果:==:65,59,48,14,59,23,37,=||=,75,86,96,
==当前堆排序结果:==:59,59,48,14,37,23,=||=,65,75,86,96,
==当前堆排序结果:==:59,37,48,14,23,=||=,59,65,75,86,96,
==当前堆排序结果:==:48,37,23,14,=||=,59,59,65,75,86,96,
==当前堆排序结果:==:37,14,23,=||=,48,59,59,65,75,86,96,
==当前堆排序结果:==:23,14,=||=,37,48,59,59,65,75,86,96,
==当前堆排序结果:==:14,=||=,23,37,48,59,59,65,75,86,96,
==当前堆排序结果:==:14,23,37,48,59,59,65,75,86,96,请按任意键继续. . .

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值