大-小顶混合堆的实现与应用(a min-max heap)

一般情况下我们使用的堆都是大顶堆或者小顶堆,其能实现在常数时间内获得数组的最大值或者最小值,同时满足在对数时间内删除和插入元素。但是如果要同时实现即能在常数时间内获得最大值和最小值,又能在对数时间内删除和插入元素,通常情况下的堆就不能满足上述要求了。为此介绍一种新的数据结构min-max heap

min-max heap 是一颗完全二叉树,但是二叉树的奇数层存的是max元素,偶数层存的是min元素,也即在以偶数层的某节点为根节的子树中,根节点最大,若在以奇数层为根节点的子树中,根节点最小。根据上述的思想构造出相应的min-max heap。

算法实现:

#include "min_max_heap.h"
#include <iostream>
#include<vector>
using namespace std;
bool min_max_heap::is_min_level(int index)
{
	int res = 0;
	index = index+1;
	while(index>1)
	{
		res = res + 1;
		index = index>>1;
	}
	if(res % 2 == 0)
		return true;
	return false;
}
bool min_max_heap::has_child(int index) const
{
	int size = data.size();
	if(2*index<size-1)
		return true;
	return false;
}
int min_max_heap::min_child(int index) const
{
	int size = data.size();
	int res=index*2+1;
	if(res<size-1 && data[res]>data[res+1])
		res++;
	return res;
}
int min_max_heap::max_child(int index) const
{
	int size = data.size();
	int res = 2*index +1;
	if(res<size-1 && data[res]<data[res+1])
		res++;
	return res;
}
bool min_max_heap::has_grandchild(int index) const
{
	int size = data.size();
	int k=2*index+1;
	if(2*k<size-1)
		return true;
	return false;
}
int min_max_heap::min_grandchild(int index) const
{
	int size = data.size();
	int res = 2*index+1;
	int left_res = 2*res+1;
	if(left_res < size-1 && data[left_res]>data[left_res + 1])
		left_re
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值