优先级队列(《编程珠玑》第14章)

优先级队列的代码,注意两点

1、在下虑的过程中,要保证right不超出界,即right<n,left显然是满足的,因为while(temp<=(n-2)>>1)中,如果left超出界限则while循环条件不满足。

2、下虑过程中,返回值要写在随后,因为不一定会执行while中的break语句,因此不要把break换成return而把最后的return丢掉!

#include<iostream>
#include<algorithm>
using namespace std;

template<typename T>
class Priqueue
{
	int maxSize;
	int n;
	T *A;
public:
	Priqueue(int _maxSize)
	{
		maxSize=_maxSize;
		n=0;
		A=new T[maxSize];
		memset(A,0,4*maxSize);
	}
	void insert(T t)
	{
		if(n==maxSize)
		{
			cout<<"已经超出最大容量"<<endl;
			return ;
		}
		A[n++]=t;
		int temp=n-1;
		while(temp>0)
		{
			if(A[(temp-1)>>1]>t)
			{
				swap(A[temp],A[(temp-1)>>1]);
				temp=(temp-1)>>1;
			}
			else
				return;
		}
	}
	T extractMin()
	{
		if(n==0)
		{
			cout<<"已经没有元素了"<<endl;
			return A[0];
		}
		swap(A[0],A[--n]);
		int temp=0;
		while(temp<=(n-2)>>1)
		{
			int left=(temp<<1)+1,right=(temp<<1)+2;
			int max2=left;
			if(right<n && A[left]>A[right])
				max2=right;
			if(A[temp]>A[max2])
			{
				swap(A[temp],A[max2]);
				temp=max2;
			}
			else
				break;
		}
		return A[n];
	}
};

int genRand()
{
	return rand()%100;
}

int main()
{
	const int N=15;
	int Arr[N];
	generate(Arr,Arr+N,genRand);
	
	Priqueue<int> pq(N);
	for(int i=0;i<N;i++)
		pq.insert(Arr[i]);
	for(int i=0;i<N;i++)
		cout<<pq.extractMin()<<endl;

	system("pause");
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值