堆排序

1)本例使用最小堆,downheap函数把frist位置的值放到合适的位置,让堆还是最小堆。
2)刚开始要从最大的有孩子的位置开始执行downheap函数,把整个数组转换为最小堆。
3)排序的方法是:取第一个元素(最小的)和最后一个元素交换,然后再转换少了一个元素的堆为最小堆,其实就是downheap交换上来的最后一个元素。
4)取到最后就是一个递减的数组了,要递增就使用最大堆。
#include <stdio.h>
#define N 9

void createheap(int a[], int frist, int last);
void downheap(int a[], int frist, int last);
void heapsort(int a[], int frist, int last);
void swap(int *x, int *y);
void printarr(int a[], int n);

void createheap(int a[], int frist, int last){
	int i;
	for(i=(last-1)/2; i>=0; i--)
		downheap(a, i, last);
}

void downheap(int a[], int frist, int last){
	int i = frist;
	int left = i*2+1;
	int temp = a[frist];
	while(left<=last){
		if(left+1<=last && a[left]>a[left+1]) left++;
		if(temp<=a[left]) break;
		swap(&a[left], &a[i]);
		i = left;
		left = i*2+1;
	}
}

void heapsort(int a[], int frist, int last){
	int i;
	for(i=last; i>0; i--){
		swap(&a[i], &a[0]);
		downheap(a, 0, i-1);
		printarr(a, i-1);
	}
}

void swap(int *x, int *y){
	int i = *x;
	*x = *y;
	*y = i;
}

void printarr(int a[], int n){
	int i;
	for(i=0; i<n; i++){
		printf("%d ", a[i]);
	}
	printf("\n");
}

int main(void){
	int a[N] = {2, 5, 3, 1, 8, 12, 15, 9, 18};
	createheap(a, 0, N-1);
	printarr(a, N);
	heapsort(a, 0, N-1);
	printarr(a, N);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值