堆
#include<bits/stdc++.h>
using namespace std;
typedef struct Heap{
int *data;
int size;
int maxsize;
}*Maxheap,*Minheap;
Maxheap Heap_init(int maxsize)
{
Maxheap h = (Maxheap)malloc(sizeof(struct Heap));
h->data = (int *)malloc((maxsize+1)*sizeof(int));
h->maxsize = maxsize;
h->size = 0;
h->data[0] = 1e8;
return h;
}
void Maxheap_insert(Maxheap h,int e)
{
int i;
i = ++h->size;
while(h->data[i/2] < e)
{
h->data[i] = h->data[i/2];
i/=2;
}
h->data[i] = e;
}
void sift(Maxheap h,int i)
{
int tmp = h->data[i];
int cld;
for(;i*2<=h->size;i=cld)
{
cld = i*2;
if((cld+1)<=h->size && h->data[cld+1]> h->data[cld])
cld += 1;
if(h->data[cld]<=tmp)
break;
else
h->data[i] = h->data[cld];
}
h->data[i] = tmp;
}
int Maxheap_delete(Maxheap h)
{
int res = h->data[1];
int tmp = h->data[h->size--];
int i,cld;
for(i=1 ; i*2<=h->size ; i = cld)
{
cld = i*2;
if( (cld+1)<=h->size && h->data[cld+1]>h->data[cld])
cld += 1 ;
if(tmp >= h->data[cld])
break;
else h->data[i] = h->data[cld];
}
h->data[i] = tmp;
return res;
}
int main()
{
Maxheap h = Heap_init(10);
int lis[6] = {16,12,32,1,343,2};
for(int i=0;i<6;i++) h->data[i+1] = lis[i];
h->size = 6;
for(int i=h->size/2;i>=1;i--) sift(h,i);
while(h->size>0)
{
cout<<Maxheap_delete(h)<<" ";
}
}