堆排序

为了用堆优化PRIM,DIJKSTRA,我先写了个堆排序的小程序,仅当练习。

/*
 * 堆排序练习题
 * mike-w
 * 2012-4-13
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define MAX_SIZE 1024
#define HEAP_SIZE (MAX_SIZE*2)
#define LC(X) ((X)*2)
#define RC(X) ((X)*2+1)
#ifndef true
#define true 1
#endif

int heap[HEAP_SIZE]; /* heap[0] indicates the size of the heap */
int f[MAX_SIZE];
int g[MAX_SIZE];
int N=1000;

int swap(int *e1, int *e2)
{
	int tmp=*e1;
	*e1=*e2;
	*e2=tmp;
	return 0;
}

int h_push(int e)
{
	if(heap[0]==0)
		heap[++heap[0]]=e;
	else
	{
		if(heap[0]==HEAP_SIZE)
			return -1;
		heap[++heap[0]]=e;
		int c=heap[0];
		int p=c/2;
		while(p>0 && heap[c]<heap[p])
			swap(heap+c,heap+p),c=p,p/=2;
	}
	return 0;
}

int h_pop(void)
{
	if(heap[0]==0)
		return -1;
	int ret=heap[1];
	swap(heap+1,heap+heap[0]);
	heap[0]--;
	int p=1,x;
	int lc,rc;
	while(true)
	{
		lc=LC(p);
		rc=RC(p);
		x=p;
		if(lc<=heap[0] && heap[x]>heap[lc])
			x=lc;
		if(rc<=heap[0] && heap[x]>heap[rc])
			x=rc;
		if(x==p)
			break;
		swap(heap+x,heap+p);
		p=x;
	}
	return ret;
}

int comp(const void *e1, const void *e2)
{
	return *((int*)e1) - *((int*)e2);
}

int main(void)
{
#ifdef FILE_INPUT
	freopen("in","r",stdin);
#endif
	int i;
	srand((unsigned)time(NULL));
	for(i=1;i<=N;i++)
		f[i]=rand();
	/* heap sort */
	for(i=1;i<=N;i++)
		h_push(f[i]);
	for(i=1;i<=N;i++)
		g[i]=h_pop();
	/* qosrt */
	qsort(f+1,N,sizeof(int),comp);
	/* check answer */
	int cnt=0;
	for(i=1;i<=N;i++)
		if(f[i]!=g[i])
			cnt++;
	printf("%d errors!\n",cnt);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值