#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct
{
int* mem;
int cursize;
int maxsize;
}HEAP,*LPHEAP;
LPHEAP creatheap(int maxsize)
{
LPHEAP newheap=(LPHEAP)malloc(sizeof(HEAP));
newheap->cursize = 0;
newheap->maxsize = maxsize+1;
newheap->mem= (int*)malloc(sizeof(int)*newheap->maxsize);
return newheap;
}
void swap(int *s,int a,int b)
{
int temp = s[a];
s[a] = s[b];
s[b] = temp;
}
void move(LPHEAP l,int child)
{
if (l->cursize == 1)return;
while (1)
{
int father = child / 2;
if (l->mem[father]<l->mem[child])
{
swap(l->mem, father, child);
}
else
{
return;
}
child = father;
if (child == 1)return;
}
}
void push(LPHEAP l, int n)
{
if (l->cursize == l->maxsize)return;
l->mem[++(l->cursize)] = n;
move(l, l->cursize);
return;
}
void pop(LPHEAP l)
{
int curpos = 1;
int childpos = curpos * 2;
while (childpos<=l->cursize)
{
int temp = l->mem[childpos];
if (childpos + 1 <= l->cursize && temp < l->mem[childpos + 1])
{
temp = l->mem[++childpos];
}
l->mem[curpos] = temp;
curpos = childpos;
childpos *= 2;
}
l->mem[curpos] = l->mem[l->cursize];
move(l, curpos);
l->cursize--;
return;
}
void ptheap(LPHEAP l)
{
for (int i = 1; i <= l->cursize; i++)
{
printf("%d\t", l->mem[i]);
}
printf("\n");
}
heap(c)
最新推荐文章于 2024-08-03 11:08:23 发布