堆排序很多时候的实际应用并不如快速排序(quick sort)那么快,但是也有很多实际的应用,例如优先级排序就是其中之一。
优先级排序可以应用到系统的调度算法中,人工智能中也经常要用到,熟悉这个算法很有好处。
不要让名字误导我们,优先级队列其实数据结构不一定就是一个普通的队列数据结构,这里的底层数据结构反而是堆,当然也可以使用其他数据结构实现。
Priority Queues应该是偏重于概念性的数据结构。
下面给出利用堆操作构建优先级排序的基本算法:
#include<iostream>
#include<vector>
#include"heapSort.h"
//包含了堆排序的操作,可以参照我博客的堆排序
using namespace std;
template<typename T>
T heapMax(const vector<T>& heap)
{
return heap[0];
}
template<typename T>
T heapExtractMax(vector<T>& heap)
{
if(heap.size()<1)
{
cerr<<"Error: heap underflow!"<<endl;
return T(0);
}
T max = heapMax(heap);
heap[0]=heap[heap.size()-1];
heap.pop_back();
maxHeapify(heap,0,heap.size());
return max;
}
template<typename T>
void heapIncreaseKey(vector<T>& heap, int i, T key)//i为C下标从0开始
{
if(i>=heap.size() || i<0) return;
if(key<heap[i])
{
cerr<<"New key is smaller than current key"<<endl;
return;
}
heap[i] = key;
while (i>0 && heapParent(i)<heap[i])
{
swap(heap[i],heap[heapParent(i)]);
i=heapParent(i);
}
}
template<typename T>
void heapDelete(vector<T>& heap, int i)//i为C下标从0开始
{
if(i>=heap.size() || i<0) return;
heap[i] = heap[heap.size()-1];
heap.pop_back();
maxHeapify(heap,i,heap.size());
}
template<typename T>
void heapPrint(const vector<T>& heap)
{
for(auto x:heap)
{
cout<<x<<" ";
}
cout<<endl;
}
void test()
{
//初始化数组
int a[8] = {2,4,7,1,4,8,9,31};
vector<int> heap(a, a+8);
//序列输出
heapPrint(heap);
//testing operation
buildMaxHeap(heap, heap.size());
//建立大顶堆后输出
heapPrint(heap);
//最大值测试
cout<<"Max = "<<heapMax(heap)<<endl;
//抽去最大值后
heapExtractMax(heap);
cout<<"After extract max:\n";
heapPrint(heap);
//增加其中一个值为100
heapIncreaseKey(heap, 3, 100);
cout<<"After increase a key to 100:\n";
heapPrint(heap);
//删除刚增加的值100一个值
heapDelete(heap, 3);
cout<<"After delete one key:\n";
heapPrint(heap);
}
int main()
{
test();
return 0;
}
总结:
熟悉堆操作的话,这个算法实现没有难度。
reference:
Introduction to Algorithm