堆排序的应用 Priority queues 优先级排序
来源:互联网 发布:cf辅助瞄准软件 编辑:程序博客网 时间:2024/05/17 07:43
堆排序很多时候的实际应用并不如快速排序(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 operationbuildMaxHeap(heap, heap.size());//建立大顶堆后输出heapPrint(heap);//最大值测试cout<<"Max = "<<heapMax(heap)<<endl;//抽去最大值后heapExtractMax(heap);cout<<"After extract max:\n";heapPrint(heap);//增加其中一个值为100heapIncreaseKey(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
- 堆排序的应用 Priority queues 优先级排序
- 堆的应用(优先级队列、海量数据处理、堆排序)
- 堆排序的应用之优先级队列的实现
- 算法导论:堆排序的应用---优先级队列
- Priority Queues优先级队列详解
- 堆排序的应用
- 堆&&堆排序&&优先级队列
- 数据结构—堆排序及其应用(优先级队列)
- android:priority优先级相同,包名次序怎么排序?
- 堆排序和优先级队列
- 优先级队列与堆排序
- 堆排序和优先级队列
- 优先级队列与堆排序
- 堆的应用之堆排序
- 堆、优先级队列和堆排序
- [数据结构] 二叉堆,堆排序,优先级队列
- 堆排序算法二(堆排序算法的应用)
- 堆排序实现优先队列(Priority queue)
- direct path read temp
- ubuntu上SVN版本升级到1.7
- SDUTOJ 1299 最长上升子序列
- Oracle DB对数据进行限制和排序
- java cmd编译后运行是区分大小写的
- 堆排序的应用 Priority queues 优先级排序
- 将TextBox数据提交到GridView显示(DataTable的应用2)
- Linux下批量修改文件及文件夹所有者及权限
- 电脑开机各种提示音
- apt-get remove删除的内容 dpkg -l还是能看到
- c++基础知识
- 不懂?求助
- 利用集成 windows身份验证在 IIS中承载此服务,以保护服务器
- mysql查询操作及正则表达式小结