【代码】c++堆的简单实现

发布时间:2020-07-01 15:50:06 作者:pawnsir
来源:网络 阅读:496

    堆对象的创建与实现的核心思想就是上调(adjustup)与下调(adjustdown)的算法思想,上调用于创建堆时,从第一个非叶子节点开始向根节点根据需求调整为大堆或者小堆

    下调如图示:

【代码】c++堆的简单实现

    当我们进行插入时,会影响堆的结构,这时我们用尾插,然后上调如图示:

【代码】c++堆的简单实现

    接下来就可以创建堆类,代码如下仅供参考:

#include<iostream>
#include<vector>
template <class T>
struct CompMax
{
	bool operator()(const T& a, const T& b)
	{
		return a > b;
	}
};
template <class T>
struct CompMin
{
	bool operator()(const T& a,const T& b)
	{
		return a < b;
	}
};

template <class T,class Com=CompMax<T> >//仿函数做模板参数,可根据需求修改比较方法
class Heap
{
public:
	Heap(const T* arr, size_t size, Com _comp)
		:comp(_comp)
	{
		_List.resize(size);
		int index = 0;
		for (index = 0; index < size; ++index)
		{
			_List[index] = arr[index];
		}
		index = (_List.size()- 2) / 2;
		while (index>=0)
			_adjustdown(index--);

	}
	void Push(const T &x)
	{
		_List.push_back(x);
		size_t index = _List.size() - 1;
		_adjustup(index);
	}
	void Pop()
	{
		_List.pop_back();
	}
	T& Top()
	{
		return _List[0];
	}
protected:
	void _adjustup(size_t index)
	{
		size_t child = index;
		size_t parent = (child - 1) / 2;
		while (child)
		{
			if (child % 2)
			{
				if (child + 1<_List.size())
					child =comp(_List[child],_List[child+1]) ? child : child + 1;
			}
			else
			{
				child = comp(_List[child] ,_List[child - 1]) ? child : child - 1;
			}
			if (!comp(_List[child],_List[parent]))
			{
				std::swap(_List[parent], _List[child]);
			}
			child = parent;
			parent = (parent - 1) / 2;

		}
	}
	void _adjustdown(size_t index)
	{
		size_t parent = index;
		size_t child = parent * 2 + 1;
		while (child < _List.size())
		{
			if (child + 1 < _List.size())
				child = comp(_List[child] , _List[child + 1]) ? child : child + 1;
			if (!comp(_List[parent], _List[child]))
			{
				std::swap(_List[child], _List[parent]);
				parent = child;
				child = (parent + 1) * 2;
			}
			else
				break;
		}

	}
protected:
	vector<T> _List;
	Com comp;
};

    如有不足希望指正,如有问题也希望提出,谢谢-3-。

推荐阅读:
  1. 堆的性质是什么?怎么实现堆?
  2. 数据结构C++实现基本的堆

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

堆.c++.堆类 c+

上一篇:[C#学习笔记]数组

下一篇:el-upload实现腾讯云视频上传功能的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》