半夜三更,编程写文章,真是妙不可言。
二叉堆是一种非常有用的数据结构。
二叉堆实际上是一颗二叉树,是一个用数组来存储的二叉树。
应用:二叉堆排序 复杂度O(N * logN)
二叉堆分为两种:最小堆,最大堆。
最小堆:父节点小于左右子节点的值。
二叉堆实际上是一颗完全二叉树,高度为 logN
设父节点在数组中的下标为x , 左子节点就是 2x 右子节点是2x+1。
设子节点(不分左右)在数组中的小标为x,父节点就是 x/2 (C语言除法向下取整)
当符合最小二叉堆后,根节点是最小值。
操作:
Insert 在二叉堆的尾部加入元素,并调整位置。
void Insert(int x)
{
int i;
heap[++n] = x;
i = n;
while(i/2>=1 && heap[i]<heap[i/2])
{
swap(heap[i/2],heap[i]);
i/=2;
}
}
数组应该从 1 开始 使用。 因为0*2 = 0 所以不能从0开始使用。
i/2>=1 边界检查
swap为交换函数。
删除根节点:
int DeleteMain()
{
int i = 1;
swap(heap[n],heap[1]);
n--;
while (i*2+1<=n && heap[i]>min(heap[i*2],heap[i*2+1]))
{
if(heap[i*2]<heap[i*2+1])
{
swap(heap[i],heap[i*2]);
i=i*2;
}
else
{
swap(heap[i],heap[i*2+1]);
i=i*2+1;
}
}
return heap[n+1];
}
注意边界检查。
一个避免越界的小技巧:
把Heap数组中每个元素都初始化为一个极大极大的值。
排序:
取根节点值后删除根节点,重复这一步,就能得到一个升序排序序列
while(n>0)
cout<<DeleteMain()<<' ';
完整代码:
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
int heap[1001];
int n = 0;
void swap(int &a,int &b)
{
int t;
t = a;
a = b;
b = t;
}
void Insert(int x)
{
int i;
heap[++n] = x;
i = n;
while(i/2>=1 && heap[i]<heap[i/2])
{
swap(heap[i/2],heap[i]);
i/=2;
}
}
int min(int x1,int x2)
{
return x1<x2?x1:x2;
}
int DeleteMain()
{
int i = 1;
swap(heap[n],heap[1]);
n--;
while (i*2+1<=n && heap[i]>min(heap[i*2],heap[i*2+1]))
{
if(heap[i*2]<heap[i*2+1])
{
swap(heap[i],heap[i*2]);
i=i*2;
}
else
{
swap(heap[i],heap[i*2+1]);
i=i*2+1;
}
}
return heap[n+1];
}
int main()
{
int num;
memset(heap,999999,sizeof(heap));
cin>>num;
for(int i = 0;i<num;i++)
{
int t;
cin>>t;
Insert(t);
}
while(n>0)
cout<<DeleteMain()<<' ';
}