为了用堆优化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;
}
31万+

被折叠的 条评论
为什么被折叠?



