小根堆的实现_by watson.long

小根堆的实现

——————————————————

#include "stdio.h"
#include
"stdlib.h"
#include
"string.h"
/*minheap struct*/
typedef
struct hnode{
int heap[100];
int currentsize;
}minheapnode,
*minheap;

/*minheap*/
void creatheap(minheap *h,int a[], int n);
void siftdown(minheap *h,int i,int m);
void siftup(minheap *h,int start);
void insert(minheap *h,int x);
int remove(minheap *h);
void heapsort(minheap *h,int a[], int n);

void main(int argc,char *argv[])
{
int data[10]={9,1,2,4,6,10,23,5,3,56};
/*sort*/
minheap h;
h
=(minheap)malloc(sizeof(minheapnode));
h
->currentsize=0;
heapsort(
&h,data,10);
}

/*heap sort*/
void heapsort(minheap *h,int a[], int n)
{
int i;
int temp;
/*creat heap*/
creatheap(h,a,n);
/*sort heap*/
for(i=(*h)->currentsize-1;i>0;i--)
{
temp
=(*h)->heap[0];
(
*h)->heap[0]=(*h)->heap[i];
(
*h)->heap[i]=temp;
siftdown(h,
0,i-1);
}
/*print sort heap*/
for(i=(*h)->currentsize-1;i>=0;i--)
{
printf(
"%d ",(*h)->heap[i]);
}
return;
}
/*creat minheap*/
void creatheap(minheap *h,int a[], int n)
{
int currentpos;
int i;
for(i=0;i<n;i++)
{
(
*h)->heap[i]=a[i];
}
(
*h)->currentsize=n;
currentpos
=((*h)->currentsize-2)/2;
while(currentpos >=0)
{
siftdown(h,currentpos,(
*h)->currentsize-1);
currentpos
--;
}
}
/*siftdown function*/
void siftdown(minheap *h,int i,int m)
{
int j;
int temp=(*h)->heap[i];
for(j=2*i+1;j<=m;j=2*j+1)
{
if( (j<m) && ( (*h)->heap[j] > (*h)->heap[j+1] ) ) j++;
if(temp <= (*h)->heap[j]) break;
else
{
(
*h)->heap[i]=(*h)->heap[j];
i
=j;
}
}
(
*h)->heap[i]=temp;
}
/*siftup function*/
void siftup(minheap *h,int start)
{
int temp,i,j;
temp
=(*h)->heap[start];
j
=start;
i
=(j-1)/2;

while(j>0)
{
if((*h)->heap <= temp) break;
else
{
(
*h)->heap[j] = (*h)->heap[i];
j
=i;
i
=(i-1)/2;
}
}

(
*h)->heap[j]=temp;
}
/*insert handle*/
void insert(minheap *h,int x)
{
if((*h)->currentsize == 100) return;
(
*h)->heap[(*h)->currentsize]=x;
siftup(h,(
*h)->currentsize);
(
*h)->currentsize++;
return;
}
/*remove handle*/
int remove(minheap *h)
{
int x=0;
if((*h)->currentsize==0) return;
x
=(*h)->heap[0];
(
*h)->heap[0]=(*h)->heap[(*h)->currentsize-1];
(
*h)->currentsize--;
siftdown(h,
0,(*h)->currentsize-1);
return x;
}
posted @ 2011-03-25 09:17  Watson.Long  阅读(388)  评论(0编辑  收藏  举报