c++手写堆

无聊尝试一下

#include<bits/stdc++.h>
using namespace std;
void adjustheap(vector<int> &b,int index,int len) //堆的向下调整
{
	//int len = b.size() - 1;//长度 
    int cur = index;//要交换的元素的当前位置 
    int left_child = 2 *cur + 1; //左儿子 
    while(left_child <= len)
    {
   		if( left_child < len && b[left_child] < b[left_child + 1])
    	{
        	left_child++;
    	}
        if(b[cur] < b[left_child]){
            swap(b[cur], b[left_child]);       
            cur = left_child;
            left_child = 2 * cur + 1;
        }
        else break;
    }
}
void upAdjust(vector<int> &b,int index)
{
	//左子节点=2*父节点+1 右子节点=2*父节点+2 
	int cur=index;
	int father=cur/2;
	if(cur%2==0) father--;
	while (cur>= 1)
	{
		// 如果父节点的权值比子节点权值小,则交换元素
		if (b[father]<b[cur])
		{
			swap(b[father],b[cur]);
			cur = father;
			father=cur/2;
			if(cur%2==0) father--;
		}
		else
		{
			break;
		}
	}
}
void makeheap(vector<int> &b,int len)
{
	
	int index = (len - 2)/2 + 1;//从最后一个非叶子节点开始建堆。
    for(int i = index ; i >= 0;i--)
    adjustheap(b,i,len);
    return ;
}
vector<int> b;
int main()
{
	int n,a;
	cin>>n;
	while(n--)
	{
		cin>>a;
		b.push_back(a);
	}
	int len = b.size() - 1;//长度 
	makeheap(b,len);
	int k=5; 
	for(int i=1;i<=k;i++)//取前k个数 
	{
		cout<<b[0]<<" ";
		swap(b[0],b[len]);
		len--;
		b.pop_back();
		adjustheap(b,0,len);
	} 
	cin>>n;
	while(n--)//插入 
	{
		cin>>a;
		b.push_back(a);
		len++;
		upAdjust(b,len);
	}
	 k=len; 
	for(int i=1;i<=k;i++)//取所有数 
	{
		cout<<b[0]<<" ";
		swap(b[0],b[len]);
		len--;
		adjustheap(b,0,len);
	} 
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值