最大堆和最小堆是二叉堆的两种形式。
最大堆:根结点的键值是所有堆结点键值中最大者的堆。
最小堆:根结点的键值是所有堆结点键值中最小者的堆。
那么如何构建一个堆呢?我们这里主要看一下小堆的构建,以及关于堆的一些操作。
首先建立一个堆:
//Heap.h文件
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#include<assert.h>
#include<stdio.h>
typedef int Datatype;
typedef struct Heap
{
int* _array;
int _size;//数据个数
int _capcity;//容量
}Heap;
void HeapInit(Heap* hp,int* a, int capcity); //初始化
void HeapDestory(Heap* hp); //销毁
void HeapPush(Heap* hp,Datatype x); //插入一数据
void HeapPop(Heap* hp); //删除一个数据
void print(Heap* hp); //显示所有的数据
void justDown(int* a, int n,int root); //向下调整算法的实现
void justUP(int* a, int n, int root); //向上调整
void HeapSort(Heap* hp); //堆排序的实现
以上接口的具体实现:
#include"Heap.h"
void HeapInit(Heap* hp, Datatype* a, int n)
{
assert(hp&&a);
hp->_array = (Datatype*)malloc(sizeof(Datatype)*n);
memcpy(hp->_array, a,sizeof(Datatype)*n);
hp->_capcity = n;
hp->_size = n;
for (int i = (n - 2) / 2; i >= 0; --i)
{
//用向下调整算法构建一个小堆
justDown(hp->_array, hp->_size, i);
}
}
void print(Heap* hp)
{
assert(hp);
for (int i = 0; i < hp->_size; ++i)
{
printf("%d ", hp->_array[i]);
}
}
void HeapDestory(Heap* hp)
{
assert(hp);
free(hp->_array);
hp->_array = NULL;
hp->_size = hp->_capcity = 0;
}
void justDown(int* a, int n, int root)
{
int parent = root;
int child = parent * 2 + 1;
while(child<n)
{
if (child + 1 < n&&a[child+1]<a[child])
{
child++;
}
if (a[parent] > a[child])
{
int tmp = a[parent];
a[parent] = a[child];
a[child] = tmp;
parent = child;
child = parent * 2 + 1;
}
else
break;
}
}
void justUP(int* a, int n, int root)
{
assert(a);
int child = root;
while (child != 0)
{
int parent = (child - 1) / 2;
if (a[parent] < a[child])
{
break;
}
else
{
int tmp = a[parent];
a[parent] = a[child];
a[child] = tmp;
child = parent;
}
}
}
void HeapPush(Heap* hp, Datatype x)
{
assert(hp);
if (hp->_size == hp->_capcity)
{
hp->_capcity *= 2;
hp->_array = realloc(hp->_array, sizeof(Datatype)*hp->_capcity);
}
hp->_array[hp->_size] = x;
hp->_size++;
justUP(hp->_array, hp->_size, hp->_size - 1);
}
void HeapPop(Heap* hp)//删除堆顶
{
assert(hp);
//将堆顶元素与堆底部最后一个元素交换
int tmp = hp->_array[0];
hp->_array[0] = hp->_array[hp->_size - 1];;
hp->_array[hp->_size - 1] = tmp;
//数组的大小减一
hp->_size--;
//重新用向下调整法,调整堆顶,将堆重新调整为小堆
justDown(hp->_array, hp->_size, 0);
}
void HeapSort(int* a,int n)
{
assert(a);
for (int i = (n - 2) / 2; i >= 0; --i)
{
justDown(a, n, i);
}
for (int i = n - 1; i >= 0; i--)
{
int tmp = a[i];
a[i] = a[0];
a[0] = tmp;
justDown(a, i, 0);
}
}
#include"Heap.h"
int main()
{
int a[] = { 9,8,2,6,3,1,5,4,7,1 };
Heap hp;
printf("堆初始化后:\n");
HeapInit(&hp,a,10);
print(&hp);
printf("\n");
printf("添加两个数据后:\n");
int i = 0;
HeapPush(&hp, i);
HeapPush(&hp, i);
print(&hp);
printf("\n");
printf("从对顶删除一个数据后:\n");
HeapPop(&hp);
print(&hp);
printf("\n");
printf("对利用堆数组进行排序后:\n");
HeapSort(hp._array,hp._size);
print(&hp);
HeapDestory(&hp);
system("pause");
return 0;
}
运行结果:
以上就是构建堆以及堆的一些操作的具体实现。上面建的是小堆,大堆道理相同,具体大家可以下去实现一下。希望以上内容会帮助到大家。