標籤:mystra 編程演算法 堆 優先順序隊列 二叉樹
堆(heap) 代碼(C)
本文地址: http://blog.csdn.net/caroline_wendy
堆(heap)作為二叉樹的重要應用, 時間複雜度O(logn), 需要熟練的寫出其代碼, 基本代碼如下, 需要背寫.
代碼:
/* * main.cpp * * Created on: 2014.7.20 * Author: spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>class Heap {static const int MAX_N = 1000;int heap[MAX_N], sz=0;public:void push(int x) {int i=sz++;while (i>0) {int p = (i-1)/2;if (heap[p]<=x) break;heap[i] = heap[p];i = p;}heap[i]=x;}int pop() {int ret = heap[0];int x = heap[--sz];int i=0;while (i*2+1<sz) {int a=i*2+1, b=i*2+2;if (b<sz && heap[b]<heap[a]) a=b; //a始終代表最小值if (heap[a]>=x) break;heap[i] = heap[a];i = a;}heap[i] = x;return ret;}};int main(void){Heap h;h.push(3);h.push(5);h.push(4);h.push(1);for (int i=0; i<4; ++i) {printf("%d ", h.pop());}printf("\n");return 0;}
輸出:
1 3 4 5
也可以使用庫函數(#include<queue>)的優先順序隊列(priority_queue), 但是取值預設得到最大值,
可以使用priority_queue<int, vector<int>, greater<int> > 輸出最小值.
代碼:
/* * main.cpp * * Created on: 2014.7.20 * Author: spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <queue>#include <vector>#include <functional>using namespace std;int main(void){priority_queue<int, std::vector<int>, std::greater<int> > pque;pque.push(3);pque.push(5);pque.push(1);pque.push(4);while (!pque.empty()) {printf("%d ", pque.top());pque.pop();}printf("\n");return 0;}
輸出:
1 3 4 5
編程演算法 - 堆(heap) 代碼(C)