算法导论—最小堆

#include <iostream>
#include <vector>

class UnderflowException { };

using namespace std;

template<typename Comparable>
class minHeap
{
public:
	explicit minHeap(int capacity=100)
	:array(capacity+1),currentSize(0)
	{}

	explicit minHeap(const vector<Comparable> &items)
	:array(items.size()+10),currentSize(items.size())
	{
		for(int i=0;i<items.size();++i)
			array[i+1]=items[i];
		buildHeap();
	}

	bool isEmpty() const 
	{
		return currentSize==0;
	}

	int currSize() const 
	{
		return currentSize;
	}

	void  print()
	{
		for(int i=1;i<=currentSize;++i)
			cout<<array[i]<<" ";
		cout<<endl;
	}

    //return the min
	const Comparable& findMin() const
	{
		if (isEmpty())
			throw UnderflowException{ };
		return array[1];
	}

	//decrease the value in position i to key
	int decreaseKey(int i,const Comparable &key)
	{
		if(key>=array[i])
		{
			cout<<"the key is greater than current key,can not change"<<endl;
			return -1;
		}
		array[i]=key;
		while(i>1&&array[i/2]>array[i])
		{
			std::swap(array[i/2],array[i]);
			i=i/2;
		}
		return 0;
	}

	//Insert the x into the heap
	void insert(const Comparable &x)
	{
		if (currentSize==array.size()-1)
			array.resize(array.size()*2);

		int hole=++currentSize;
		array[hole]=INT_MAX;
		decreaseKey(hole,x);
	}

	//delete the minMum and return it
	int deleteMin()
	{
		if(isEmpty())
			throw UnderflowException{ };
		Comparable tmp=array[1];
		std::swap(array[1],array[currentSize--]);
		minHeapIfy(1);
		return tmp;
	}

	//minHeapSort
	void minHeapSort(vector<Comparable> &vec)
	{
		while(currentSize)
		{
			Comparable tmp=deleteMin();
			vec.push_back(tmp);
		}
	}



private:
	int currentSize;
	vector<Comparable> array;


	void buildHeap()
	{
		for(int i=currentSize/2;i>0;--i)
			minHeapIfy(i);
	}


	void minHeapIfy(int i)
	{
		int child;
		Comparable tmp=std::move(array[i]);
		for(;i*2<=currentSize;i=child)
		{
			child=i*2;
			if(child!=currentSize&&array[child]>array[child+1])
				++child;
			if(array[child]<tmp)
				array[i]=std::move(array[child]);
			else
				break;
		}
		array[i]=std::move(tmp);
	}
};


int main()
{
	cout<<INT_MAX<<endl;
	vector<int> vec{9,8,7,6,5};
	minHeap<int> heap{vec};
	heap.print();
	cout<<heap.currSize()<<endl;

	heap.insert(1);
	cout<<heap.currSize()<<endl;
	heap.print();

	vector<int> vec2;
	heap.minHeapSort(vec2);
	for(auto v:vec2)
		cout<<v<<" ";
	cout<<endl;




}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值