堆的簡單實現(仿函數)

堆數據結構是一種數組對象,它可以被視爲一棵完全二叉樹結構。


最大堆:每個父節點的都大於孩子節點。

最小堆:每個父節點的都小於孩子節點。


堆結構的二叉樹存儲是:

650) this.width=650;" src="http://s4.51cto.com/wyfs02/M02/80/06/wKiom1c0c7LBwZGrAAB2OesT9u0148.png" title="QQ截圖20160512201426.png" alt="wKiom1c0c7LBwZGrAAB2OesT9u0148.png" />


代碼實現如下:

#pragma once

#include <iostream>
#include <vector>
#include <assert.h>

using namespace std;

//仿函數
template <typename T>
struct Greater
{
	bool operator() (const T & l, const T & r)
	{
		return l > r;
	}
};

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

//模板參數
template <typename T,typename comer=Greater<T> >

class Heap
{
public:
	//無參構造函數
	Heap()
		:_a(NULL)
	{}
	//有參構造函數
	Heap(T * a, size_t size)
	{
		assert(a);
		//先把數據保存在vector中
		for (size_t i = 0; i < size; i++)
		{
			_a.push_back(a[i]);
		}
		//建堆
		for (int j = ((_a.size() - 2) / 2); j >= 0; j--)
		{
			//向下調整算法
			_AdjustDown(j);
		}
	}

	void Push(const T x)//插入元素
	{
		_a.push_back(x);
		_AdjustUp(_a.size() - 1);
	}

	void Pop()//刪除元素
	{
		assert(_a.size() > 0);
		swap(_a[0], _a[_a.size() - 1]);
		_a.pop_back();
		_AdjustDown(0);
	}

	size_t Size()
	{
		return _a.size();
	}

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

	void print()
	{
		for (int i = 0; i < _a.size(); i++)
		{
			cout << _a[i] << " ";
		}
		cout << endl;
	}

protected:
	//向下調整算法
	void _AdjustDown(size_t parent)
	{
		size_t child = parent * 2 + 1;
		comer com;
		while (child < _a.size())
		{
			//找出左右孩子中比較大的
			if (child + 1 < _a.size() && com(_a[child + 1] , _a[child]))
			{
				child++;
			}
			//比較父親和孩子的大小
			if (com (_a[child],_a[parent]))
			{
				swap(_a[child], _a[parent]);
				parent = child;
				child = parent * 2 + 1;
			}
			else
			{
				break;
			}
		}
	}

	//向上調整算法
	void _AdjustUp(size_t child)
	{
		assert(child < _a.size());
		int parent = (child - 1) / 2;
		comer com;
		while (child > 0)
		{
			//只需看父節點<根節點
			if (com(_a[child], _a[parent]))
			{
				swap(_a[child], _a[parent]);
				child = parent;
				parent = (child - 1) / 2;
			}
			else
			{
				break;
			}
		}
	}

private:
	vector <T> _a;
};

需要學習的也就是向上以及向下調整算法。

歡迎大家提出寶貴的意見。

測試用例如下:

void Test()
{
	int a[] = { 10, 11, 13, 12, 16, 18, 15, 17, 14, 19 };
	Heap<int,Less<int> > hp1(a, sizeof(a) / sizeof(a[0]));

	hp1.print();
	cout << hp1.Size() << endl;
	cout << hp1.Empty() << endl;

	hp1.Push(20);

	hp1.print();
	cout << hp1.Size() << endl;
	cout << hp1.Empty() << endl;

	hp1.Pop();

	hp1.print();
	cout << hp1.Size() << endl;
	cout << hp1.Empty() << endl;

650) this.width=650;" src="http://s1.51cto.com/wyfs02/M00/80/06/wKiom1c0dQKzwrL-AAAHsjLmYBg342.png" title="QQ截圖20160512202003.png" alt="wKiom1c0dQKzwrL-AAAHsjLmYBg342.png" />

本文出自 “不斷進步的空間” 博客,請務必保留此出處http://10824050.blog.51cto.com/10814050/1772805

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章