《编程珠玑》代码之路20:优先队列的源码实现

在 《编程珠玑》代码之路19:堆的概念和隐式堆实现(https://blog.csdn.net/beijixiong5622/article/details/85001300)中,我们给出了堆的调整算法,主要是通过下沉和上浮操作使得因改变一个元素打乱结构的堆复原。

优先队列顾名思义是一个队列,不同之处在于,它每次弹出的是最小值(最大值),在C++等高级语言中,优先队列就是通过堆来实现的,源码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>

using namespace std;

template<class T>
class priQueue{
private:
	int n, maxSize;
	T *x;

	void swap(int i, int j){
		T t = x[i];
		x[i] = x[j];
		x[j] = t;
	}

public:
	priQueue(int m){
		maxSize = m;
		x = new T[maxSize + 1];
		n = 0;
	}

	void insert(T t){
		int i, p;
		x[++n] = t;
		for (int i = n; i > 1 && x[p = i / 2] > x[i]; i = p){
			swap(p, i);
		}
	}

	T pop(){

		int i, c;
		T t = x[1];
		x[1] = x[n--];
		for (i = 1; (c = 2 * i) <= n; i = c){
			if (c + 1 < n && x[c + 1] < x[c]){
				c++;
			}

			if (x[i] < x[c]){
				break;
			}

			swap(c, i);
		}
		return t;
	}
};

int main(){

	priQueue<int> que(20);

	que.insert(1);
	que.insert(3);
	que.insert(56);
	que.insert(34);
	que.insert(12);
	que.insert(13);

	cout << que.pop() << endl;
	cout << que.pop() << endl;

	que.insert(2);

	cout << que.pop() << endl;

	return 0;
}

猜你喜欢

转载自blog.csdn.net/beijixiong5622/article/details/85015018