堆的实现

堆的实现


堆的介绍:
二叉堆的底层数据结构为数组,它可以被视为完全二叉树结构;

堆的特性:
1、父结点总是大于(或小于)子结点
2、每个节点的左子树和右子树都是一个最大堆(或最小堆)

如图:



堆的代码实现如下:
提示:本程序利用 仿函数模板实现的堆,大堆与小堆的代码只是一个大于小于号的问题,所以我通过模板传参,实现大小堆,代码复用了起来

<span style="font-size:18px;">#pragma once

#include<iostream>
#include<assert.h>
using namespace std;
#include<vector>

//仿函数

template <class T>
struct GreaterCompare
{
	bool operator()(const T& l, const T& r)
	{
		return l > r;
	}
};

template<class T>
struct LessCompare
{
	bool operator()(const T& l, const T& r)
	{
		return l < r;
	}
};

template <class T,class Compare = GreaterCompare<T>>
class Heap
{
public:
	Heap()
	{}

	Heap(const T* arr, int len)
	{
		assert(arr);
		assert(len > 0);
		int i = 0;
		//传入数据
		for (; i < len; ++i)
		{
			_arr.push_back(arr[i]);
		}
		//建堆
		i = _arr.size();
		for (i = (i - 2) / 2; i >= 0;--i)
		{
			_AdjustDown(i);
		}
	}

	int Size()
	{
		return _arr.size();
	}

	bool Empty()
	{
		return _arr.empty();
	}

	//插入数据
	void Push(const T& x)
	{
		_arr.push_back(x);
		_AdjustUp(_arr.size()-1);
	}

	//删除数据
	void Pop()
	{
		if (!Empty())
		{
			swap(_arr[0], _arr[_arr.size() - 1]);
			_arr.pop_back();
			_AdjustDown(0);
		}
	}

	T Top()
	{
		return _arr[0];
	}

	~Heap()
	{}
protected:
	void _AdjustDown(int root)
	{
		Compare com;
		int child = root * 2 + 1;
		while (child < (int)_arr.size())
		{
			if (child + 1 < (int)_arr.size() && com(_arr[child + 1], _arr[child]))
				++child;
			if (com(_arr[child] , _arr[root]))
			{
				swap(_arr[child], _arr[root]);
				root = child;
				child = 2 * root + 1;
			}
			else
			{
				break;
			}
		}
	}

	void _AdjustUp(int child)
	{
		Compare com;
		int root = (child - 1) / 2;
		while (child > 0)
		{
			if (com(_arr[child], _arr[root]))
			{
				swap(_arr[child], _arr[root]);
				child = root;
				root = (child - 1) / 2;
			}
			else
			{
				break;
			}
		}
	}
private:
	vector<T> _arr;
};

void TestHeap()
{
	int a[] = { 10, 11, 13, 12, 16, 18, 15, 17, 14, 19 };
	//默认是大堆
	Heap<int> hp(a, sizeof(a) / sizeof(a[0]));
	//传参小堆的调用
	//Heap<int,LessCompare<int>> hp(a, sizeof(a) / sizeof(a[0]));

	hp.Push(20);
	hp.Pop();
}</span>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值