#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <iostream>
using namespace std;
typedef struct Heap
{
int* data;
int size;
int length;
}Heap;
Heap* initHeap(int n)
{
Heap* h = (Heap*)malloc(sizeof(Heap));
h->data = (int*)malloc(sizeof(int) * n);
h->size = n;
h->length = 0;
return h;
}
void freeHeap(Heap* h)
{
if (!h) return;
free(h->data);
free(h);
return;
}
bool push(Heap* h, int val)
{
if (!h) return false;
if (h->size == h->length) return false;
h->data[h->length] = val;
//调整插入的位置
int index = h->length;
while (index > 0 && h->data[index] > h->data[(index - 1) / 2])
{
swap(h->data[index], h->data[(index - 1) / 2]);
index = (index - 1) / 2;
}
h->length++;
return true;
}
void downAdjust(int* arr, int index, int length)
{
while (index * 2 + 1 < length)
{
int tmp = index, l = index * 2 + 1, r = index * 2 + 2;
//如果左孩子比父节点大,记录左孩子位置
if (arr[l] > arr[tmp]) tmp = l;
//如果右孩子比父节点和左孩子的较大值还大,记录右孩子位置
if (r<length && arr[r]>arr[tmp]) tmp = l;
//如果父节点就是最大的,堆平衡了
if (tmp == index) break;
//交换父节点和最大孩子的值,
swap(arr[tmp], arr[index]);
//记录父节点当前的位置
index = tmp;
}
return;
}
bool isEmpty(Heap* h)
{
return !h || !h->length;
}
int pop(Heap* h)
{
int ret = h->data[0];
h->data[0] = h->data[h->length - 1];
h->length--;
downAdjust(h->data, 0, h->length);
return ret;
}
void showHeap(Heap* h)
{
printf("Heap:[");
for (int i = 0; i < h->length; i++)
{
i&& printf(",");
printf("%d", h->data[i]);
}
printf("]\n");
}
int main()
{
srand(time(0));
#define HEAPLEN 10
Heap* h = initHeap(HEAPLEN);
int cnt = HEAPLEN;
while (cnt--)
{
int val = rand() % 100;
push(h, val);
}
showHeap(h);
printf("pop: [");
while (!isEmpty(h))
{
printf("%d ", pop(h));
}
printf("]\n");
freeHeap(h);
#undef HEAPLEN
return 0;
}
08-03
694
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)