#include <iostream> using namespace std; #include <vector> #include <assert.h> //仿函數(shù) template<class T> struct Less { bool operator()(const T& left, const T& right) { return left < right; } }; template<class T> struct Greater { bool operator()(const T& left, const T& right) { return left > right; } }; template<class T, class Compare = Less<T>>//默認(rèn)為小堆 class Heap { public: Heap() {} Heap(const T* array, size_t size) { for (size_t i = 0; i < size; ++i) { _a.push_back(array[i]); } for (int i = (_a.size()-2)/2; i >= 0; --i) { _AdjustDown(i); } } void Push(const T& x) { _a.push_back(x); _AdjustUp(_a.size()-1); } void Pop() { assert(!_a.empty()); swap(_a[0], _a[_a.size()-1]); _a.pop_back(); _AdjustDown(0); } T& GetTop() { assert(!_a.empty()); return _a[0]; } bool Empty() { return _a.empty(); } size_t Size() { return _a.size(); } void Print() { for (size_t i = 0; i < _a.size(); ++i) { cout<<_a[i]<<" "; } cout<<endl; } protected: //向下調(diào)整 void _AdjustDown(size_t parent) { Compare compare; size_t child = parent*2 + 1; while (child < _a.size()) { //比較左右孩子 if (child+1 < _a.size() && compare(_a[child+1], _a[child])) { ++child; } if (compare(_a[child], _a[parent])) { swap(_a[child], _a[parent]); parent = child; child = parent*2 + 1; } else { break; } } } //向上調(diào)整 void _AdjustUp(size_t child) { Compare compare; size_t parent = (child-1)/2; while (child > 0) { if (compare(_a[child], _a[parent])) { swap(_a[parent], _a[child]); child = parent; parent = (child-1)/2; } else { break; } } } protected: vector<T> _a; }; void Test() { int a[10] = {10, 11, 13, 12, 16, 18, 15, 17, 14, 19}; Heap<int, Greater<int>> hp1(a, sizeof(a)/sizeof(a[0])); hp1.Print(); cout<<"size:"<<hp1.Size()<<endl; cout<<"top:"<<hp1.GetTop()<<endl; cout<<"empty:"<<hp1.Empty()<<endl; } int main() { Test(); return 0; }
10年積累的成都網(wǎng)站制作、網(wǎng)站設(shè)計經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識你,你也不認(rèn)識我。但先網(wǎng)站制作后付款的網(wǎng)站建設(shè)流程,更有加查免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
文章標(biāo)題:C++實現(xiàn)堆
網(wǎng)頁鏈接:http://www.rwnh.cn/article2/jgjcoc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、App開發(fā)、面包屑導(dǎo)航、品牌網(wǎng)站制作、定制網(wǎng)站、網(wǎng)站收錄
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)