堆的创建、插入、删除

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cell_KEY/article/details/52567160

堆的概念:

如果有一个关键码的集合K = {k0,k1, k2,…,kn-1},把它的所有元素按完全二叉树 的顺序存储方式存储在一个一维数组中,并满足:Ki <= K2*i+1 且 Ki<= K2*i+2 (Ki >= K2*i+1 且 Ki >= K2*i+2)  i = 0,1,2…,则称这个堆为最小堆(或最大 堆)。

                              

最小堆:任一结点的关键码均小于等于它的左右孩子的关键码,位于堆顶结点的关键码最小 

最大堆:任一结点的关键码均大于等于它的左右孩子的关键码,位于堆顶结点的关键码最大

堆的创建:

                                      

将上述二叉树调整为最小堆的结构: 从结点(ArraySize-2)/2开始调整,将每一棵子树都调整成一棵最小堆结构

堆的插入&删除
【插入】  

堆的插入每次都在已经建成的而最小堆的后面插入,但插入之后,有可能破坏了对的 结构,这时就需要对堆自下而上的对其调整。
【删除】  

堆的删除是:从堆中删除堆顶元素。移除堆顶元素之后,用堆的最后一个节点填补取 走的堆顶元素,并将堆的实际元素个数减1。但用最后一个元素取代堆顶元素之后有可 能破坏堆,因此需要将对自顶向下调整,使其满足最大或最小堆。

#include<iostream>
#include<vector>
using namespace std;
template<class T>
class Heap
{
public:
	Heap(const T*arr, const T size)
	{
		for (int i = 0; i < size; i++)
			_heap.push_back(arr[i]);
		int _size = _heap.size();
		int begin = (_size - 2) / 2;//取第一个非叶子节点
		for (int root = begin; root >= 0; root--)
		{
			AdjustDown(root);
		}
	}
	void Insert(const T& value)
	{
		_heap.push_back(value);
		int leaf = _heap.size() - 1;
		AdjustUp(leaf);
	}
	bool Empty()
	{
		return _heap.empty();

	}
	//删除第一个元素时,使其和最后一个替换 删除最后一个,然后自顶向下调整
	void Remove()
	{
		swap(_heap[0], _heap[_heap.size() - 1]);
		_heap.pop_back();
		AdjustDown(0);
	}
	int Size()
	{
		return _heap.size();
	}
	T& GetTop()
	{
		if (!_heap.empty())
		{
			return _heap[0];
		}
	}
protected:
	void AdjustDown(int root)
	{
		int size = _heap.size();
		int child = root * 2 + 1;//该节点的左孩子
		while (child<size)
		{
			if (child + 1 < size&&_heap[child + 1] < _heap[child])
				child = child + 1;
			if (_heap[child] < _heap[root])
			{
				swap(_heap[child], _heap[root]);
				root = child;
				child = root * 2 + 1;
			}
			else
				break;
		}
	}
	void AdjustUp(int leaf)
	{
		int root = (leaf - 1) / 2; //取父亲节点
		while (leaf > 0)
		{
			if (_heap[leaf] < _heap[root])
			{
				swap(_heap[leaf], _heap[root]);
				leaf = root;
				root = (leaf - 1) / 2;
			}
			else
			{
				break;
			}
			
		}
	}
private:
	vector<T> _heap;
};


猜你喜欢

转载自blog.csdn.net/Cell_KEY/article/details/52567160