c++实现最大堆和最小堆

注释部分已经说明如何建立最大堆

template
class MinHeap
{
public:
	MinHeap()
	{
		_maxSize = 0;
		_index   = -1;
		_minHeap = NULL;
	}

	MinHeap(int maxsize)
	{
		_maxSize = maxsize;
		_index   = -1;
		_minHeap = new T[maxsize];
	}

	MinHeap(MinHeap& h)
	{
		_maxSize = h._maxSize;
		_index   = h._index;
		for (int i = 0; i < h._index; i++)
			_minHeap[i] = h._minHeap[i];
	}

	~MinHeap()
	{
		delete [] _minHeap;
	}

	T* GetMinHeap()
	{
		return _minHeap;
	}

	bool IsEmpty()
	{
		return _index == -1;
	}
	bool IsFool()
	{
		return _index == _maxSize;
	}

	bool Add(T x)
	{
		if (IsFool())
			return false;

		_index++;
		_minHeap[_index] = x;
		return true;
	}

	void CreatMinHeap()
	{
		if (IsEmpty())
			return;

		for (int i = (_index - 1)/2; i > -1; i--)
		{
			AdjustDown(i);
		}
	}

	void AdjustDown(int index)
	{
		if (IsEmpty())
			return;
		
		int temp;
		int flag = 0;

		while ((index*2+1)<=_index && flag == 0)
		{
			if (_minHeap[index] > _minHeap[index*2+1]) //将此处及以下几处的大于号改成小于号,则最小堆就变成最大堆
				temp = index*2+1;
			else
				temp = index;

			if (index*2+2 <= _index)
			{
				if (_minHeap[temp] > _minHeap[index*2+2])//将此处及以下几处的大于号改成小于号,则最小堆就变成最大堆
					temp = index*2+2;
			}
			
			if (temp != index)
			{
				T t             = _minHeap[temp];
				_minHeap[temp]  = _minHeap[index];
				_minHeap[index] = t;
				index = temp;

			}
			else
				flag = 1;

		}

	}

	void AdjustUp(int index)
	{
		if (index < 0 || index == 0)
			return;

		int flag = 0;
		while (index != 0 || flag == 0)
		{
			int i = (index-1)/2;
			if (_minHeap[i] > _minHeap[index])//将此处及以下几处的大于号改成小于号,则最小堆就变成最大堆
			{
				T t             = _minHeap[i];
				_minHeap[i]     = _minHeap[index];
				_minHeap[index] = t;
			}
			else
				flag = 1;

			index = (index-1)/2;
		}
			
	}

	bool InsertNode(const T& v)
	{
		if ((_index + 1) < _maxSize)
		{
			_index++;
			_minHeap[_index] = v;
			AdjustUp(_index);
			return true;
		}
		else
			return false;
	}
	bool DeleteNode(T& v)
	{
		if (IsEmpty())
			return false;

		v = _minHeap[0];
		_minHeap[0] = _minHeap[_index];
		_index--;

		AdjustDown(_index);
		
	}

	/*
		1、如果是最小堆,则HeapSort实现从大到小
		2、如果是最大堆,则HeapSort实现从小到大
	*/
	void HeapSort()
	{
		while (_index > -1)
		{
				
				T temp           = _minHeap[0];
				_minHeap[0]      = _minHeap[_index];
				_minHeap[_index] = temp;

				_index--;
				AdjustDown(0);
				

		}
	}

private:
	T*			_minHeap;
	int			_index;
	int         _maxSize;
};

int main()
{
	MinHeap jb(10);
	jb.Add(20);
	jb.Add(18);
	jb.Add(19);
	jb.Add(13);
	jb.Add(42);
	jb.Add(5);
	jb.CreatMinHeap();
	jb.HeapSort();
	int *p=jb.GetMinHeap();
	printf("整理为最小堆:\n");
	for (int i = 0;i < 6;i++) {
		printf("%d\n",p[i]);
	}
	
	getchar();

	return 0;
}


你可能感兴趣的:(算法)