一日一码06——堆排序

这个堆排序算法,采用的是最大堆;最小堆,通常在构造最小优先队列时使用。


//堆排序	2013/09/29

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

int heapSize = 0;

void swap(int *a, int *b){
	int tmp = *a;
	*a = *b;
	*b = tmp;
}

int left(int p){
	return 2*p+1; //下标从0开始的写法,如果从1开始,左子节点为2*p
}

int right(int p){
	return 2*p + 2;
}

int parent(int n){
	return (n - 1)/2;
}

void maxHeapify(int *a, int i){
	int l,r,largest;
	l = left(i);
	r = right(i);
	if ( l < heapSize && a[l] > a[i]) //不要写成l <= heapSize,会导致排序出错
	{
		largest = l;
	}else{
		largest = i;
	}

	if ( r < heapSize && a[r] > a[largest])
	{
		largest = r;
	}

	if (largest != i)
	{
		swap(&a[largest],&a[i]);
		maxHeapify(a,largest);
	}
}

void buildMaxHeap(int *a){
	int i;
	for (i = (heapSize - 1) / 2; i >= 0 ; --i)     //关键点,避免了对叶子节点进行maxHeapify操作
	{
		maxHeapify(a,i);
	}
}

void heapSort(int *a){
	int i;
	for (i = heapSize - 1; i > 0; --i)
	{
		swap(&a[i],&a[0]);
		heapSize--;			//千万不要漏了
		maxHeapify(a,0);
	}
}

int initArr(int** a){
	int i,n;
	srand(time(NULL));
	
	printf("Input the size of array:");
	scanf("%d",&n);
	*a = (int *)malloc(n*sizeof(int));

	for(i = 0; i < n; i++){
		(*a)[i] = rand()%100; 
	}
	return n;
}

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

void main(){
	int* arr;
	int n;

	n = initArr(&arr);
	heapSize = n;
	printArr(arr,n);
	// maxHeapify(arr,0);
	buildMaxHeap(arr);
	heapSort(arr);
	printArr(arr,n);
	//printf("%d\n",0/2 );
	


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值