【代碼】c++堆的簡單實現

    堆對象的建立與實現的核心思想就是上調(adjustup)與下調(adjustdown)的算法思想,上調用於建立堆時,從第一個非葉子節點開始向根節點根據需求調整爲大堆或者小堆
ios

    下調如圖示:算法

wKiom1cvCpfjuPkkAAAkCLyIQjQ600.png

    當咱們進行插入時,會影響堆的結構,這時咱們用尾插,而後上調如圖示:
ide

wKiom1cvDRehwFD4AAAlAV7a9cM800.png

    接下來就能夠建立堆類,代碼以下僅供參考:
函數

#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-。
對象

相關文章
相關標籤/搜索