所谓堆,就是一棵完全二叉树,对于二叉树的任意一个节点node,它的左右孩子(如果有的话)都和node满足同一种关系,如都大于node(小根堆)或都小于node(大根堆),但是左右孩子之间的关系没有要求。通常用数组来实现一个堆,对于每一个节点,它的下标*2就是左孩子(如果有的话),左孩子下标再加一就是右孩子(如果有的话),操作起来很方便。堆的构造是每插入一个元素都对元素进行适当的上浮调整,使之满足堆的条件,时间复杂度为O(n*logn)。如果每次删除堆顶并输出,并将堆的最后一个元素移到堆顶后再对其进行下沉调整重新形成一个堆,循环操作直到堆为空,那么最后输出的序列一定是有序的,这就是堆排序。
/*
堆和堆排序
*/
#include<map>
#include<set>
#include<list>
#include<queue>
#include<stack>
#include<ctime>
#include<cmath>
#include<string>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define MAXN 100005
#define MAX_INT 2147483647
#define FA(x) (x>>1)
#define LC(x) ((x<<1))
#define RC(x) ((x<<1)|1)
#define MID(x,y) ( (x + y) >> 1 )
#define TIME_BEGIN double t1 = clock()
#define TIME_END double t2 = clock();printf("\n%.2lfms\n",t2-t1)
using namespace std;
int size,top = 1;
int heap[MAXN];
bool cmp(int a,int b)//关键字比较函数,目前是构造小根堆
{
return a < b;
}
void up(int id)//上浮操作
{
if(id == 1)
return ;
if(!cmp(heap[FA(id)] , heap[id]))
{
swap(heap[FA(id)] , heap[id]);
up(FA(id));
}
}
void down(int id)//下沉操作
{
if(RC(id) <= size)//当前节点有左右孩子
{
if(cmp(heap[LC(id)] , heap[RC(id)]) && cmp(heap[LC(id)] , heap[id]))
{
swap(heap[LC(id)] , heap[id]);
down(LC(id));
}
else if(!cmp(heap[LC(id)] , heap[RC(id)]) && cmp(heap[RC(id)] , heap[id]))
{
swap(heap[RC(id)] , heap[id]);
down(RC(id));
}
}
else if(LC(id) <= size)//当前节点只有左孩子
{
if(cmp(heap[LC(id)] , heap[id]))
{
swap(heap[LC(id)] , heap[id]);
down(LC(id));
}
}
}
void insert(int t)//插入新元素
{
heap[++size] = t;
up(size);//上浮调整堆
}
int dele()//删除并返回堆顶
{
int tmp = heap[top];
heap[top] = heap[size--];
down(top);//下沉调整堆
return tmp;
}
void print(int num)//按层遍历
{
int k = 1,cnt = 0,kk = 0;
while(num)
{
num -= k;
while(kk < k)
{
cnt ++; kk ++;
cout<<heap[cnt]<<" ";
}
kk = 0;
cout<<endl;
k = min(k<<1, num);
}
}
int main()
{
TIME_BEGIN;
freopen("./heap.in" , "r" , stdin);
int t;
while(cin>>t)
{
insert(t);//插入堆元素
}
print(size);//按层遍历整个堆
cout<<"==============="<<endl;
while(size)
{
cout<<dele()<<" ";//依次弹出堆顶进行排序
}
cout<<endl<<"==============="<<endl;
TIME_END;
return 0;
}
测试数据:15 1 2 9 8 7 6 3 11 13 5 12 4 10 14
输出结果:
1
3 2
8 5 4 6
15 11 13 9 12 7 10 14
===============
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
===============
0.00ms
--------------------------------
Process exited with return value 0
Press any key to continue . . .