1首先要明白什么是堆,跑程序经常会遇到堆崩溃,还好这个不是反应堆。堆是一段连续的内存,先看看用二叉树描述堆,用数组存储
大顶堆的意思就是父节点大于孩子节点,那小顶堆的意思也不难理解喽。
数组的第一个空间下标为0,一般不用,这时你会惊奇的发现子节点的序号/2就是父节点的序号!
2堆的插入
首先从尾节点开始和父节点比较比父节点大就和父节点换位置,一直比到比父节点小或等,也可以理解为向上渗透
3堆的实现:(主要是对数组的操作)
代码:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>
typedef struct
{
int cursize;//当前元素个数
int* mem; //堆的内存
int maxSize;//最大元素个数
}HEAP,*LPHEAP;
//创建堆
LPHEAP CreateHeap(int maxSize)
{
LPHEAP heap = (LPHEAP)malloc(sizeof(HEAP));//申请内存
assert(heap);//判断堆是否申请成功
//堆的初始化
heap->cursize = 0;
heap->maxSize = maxSize;
heap->mem = (int*)malloc(sizeof(int) * heap->maxSize);
assert(heap->mem);//判断堆的内存是否申请成功
return heap;
}
//获取堆当前大小
int size(LPHEAP heap)
{
return heap->cursize;
}
//判断堆是否为空
int empty(LPHEAP heap)
{
return heap->cursize == 0;
}
//调整堆
void movecorect(LPHEAP heap, int curPos)
{
while (curPos > 1)//如果堆当前下标大于一
{
int max = heap->mem[curPos];//获取当前下标数据
int parentPos = curPos / 2;//子节点序号/2为父节点序号
if (max > heap->mem[parentPos])//如果子节点数据大于父节点数据
{//子父节点数据交换
heap->mem[curPos] = heap->mem[parentPos];
heap->mem[parentPos] = max;
curPos = parentPos;//下标逐次向一靠拢
}
else//其他情况,不需要调整堆
break;
}
}
//入堆
void insertHeap(LPHEAP heap, int data)
{
//判断堆是否已经满了,注意下标0不用
if (heap->cursize == heap->maxSize-1)
return;
//存储数据,直接放数组最后就行
heap->mem[++heap->cursize] = data;
//大顶堆,向上渗透
movecorect(heap, heap->cursize);
}
//出堆
int popHeap(LPHEAP heap)
{
int max = heap->mem[1]; //第一个元素肯定是最大
int curPos = 1; //当前节点即父节点
int childPos = curPos * 2;//子节点=父节点*2
while (childPos <= heap->cursize)
{
int temp = heap->mem[childPos];
//横向比较找最大值
if (childPos + 1 <= heap->cursize && temp < heap->mem[childPos + 1])
{
temp = heap->mem[++childPos]; //往右边走
}
heap->mem[curPos] = temp;
curPos = childPos;
childPos *= 2;
}
heap->mem[curPos] = heap->mem[heap->cursize];
movecorect(heap, curPos);
heap->cursize--;
return max;
}
int main()
{
srand((unsigned int)time(NULL));
LPHEAP heap = CreateHeap(11);
for (int i = 0; i < 11; i++)
{
insertHeap(heap, rand() % 100);
}
printf("堆中数据:\n");
for (int i = 1; i < 11; i++)
{
printf("%d\t", heap->mem[i]);
}
printf("\n");
printf("堆排序:\n");
while (!empty(heap))
{
printf("%d\t", popHeap(heap));
}
printf("\n");
return 0;
}
输出: