小堆插入
void AdjustUp(int* p,int size,int loc)//传结构体中的数组
{
assert(p);
int parent = (loc - 1) / 2 ;
while(loc)
{
if (p[loc] < p[parent]) //大堆 >
{
Swap(&p[loc], &p[parent]);
loc = parent;
parent = (loc - 1) / 2;
}
else
{
break;
}
}
}
void HeapPush(hp* p, int x)
{
int newcap = p->cap == 0 ? 4 : p->cap * 2;
int* tmp = (int*)realloc(p->a,sizeof(int) * newcap);
assert(tmp);
p->a = tmp;
p->a[p->size] = x;
p->cap = newcap;
p->size++;
AdjustUp(p->a,p->size,p->size-1);
}
小堆删除
void AdjustDown(int* a, int sz)
{
int cur = 0;
int child = 1;
while(child<=sz)//sz是数组最后一个元素的下标,
{
if (a[child + 1] < a[child]) //大堆>
child++;
if (a[cur] > a[child]&&child<=sz) //大堆a[cur]<a[child]
{
Swap(&a[cur], &a[child]);
cur = child;
child = cur * 2 + 1;
}
else
break;
}
}
void HeapPop(hp* p)
{
assert(p);
assert(p->a);
Swap(&p->a[0], &p->a[p->size - 1]);
p->size--;
AdjustDown(p->a, p->size-1);
}