最小堆實現代碼

參考算法導論、數據結構相關書籍,寫得最小堆實現的源代碼如下:

  1 //
  2 //--最小堆實例
  3 //
  4 
  5 #include <iostream>
  6 #include <vector>
  7 #include <string>
  8 using namespace std;
  9 
 10 template<typename Comparable>
 11 class minHeap
 12 {
 13 public:
 14     explicit minHeap(int capacity = 0);//顯示構造函數,只能用于對象的構造而不能用于隱式轉換
 15     explicit minHeap(const vector<Comparable>& items);
 16     
 17     bool isEmpty() const;
 18     Comparable min() const;
 19     
 20     void insert(const Comparable& key); //插入關鍵字
 21     Comparable extractMin(); //獲得最小值并將其刪除
 22     void decreaseKey(int i,Comparable key); //增加優先級
 23     void increaseKey(int i,Comparable key); //相當于降低優先級
 24     void remove(int p); //刪除堆中位置p的結點,例如OS中非正常終止進程
 25 private:
 26     int heapsize;
 27     vector<Comparable> array;
 28     
 29     void build_heap(); //建堆
 30     void minHeapify(int hole); //從位置hole處向下篩選方法
 31 };
 32 
 33 template<typename Comparable>
 34 Comparable minHeap<Comparable>::min() const
 35 {
 36     return array[1];
 37 }
 38 
 39 template<typename Comparable>
 40 Comparable minHeap<Comparable>::extractMin() //獲取最小值并將其刪除
 41 {
 42     if (heapsize<1)
 43         cout << "error" << endl;
 44     else
 45     {
 46         Comparable min = array[1];
 47         array[1] = array[heapsize];
 48         --heapsize;
 49         minHeapify(1);
 50         return min;
 51     }
 52 }
 53 
 54 template<typename Comparable>
 55 void minHeap<Comparable>::decreaseKey(int i,Comparable key)
 56 {
 57     if (key>array[i])
 58         cout << "new key is larger than current key!" << endl;
 59     else
 60     {
 61         array[i] = key;
 62         for(; i>1 && array[i]<array[i/2]; i /= 2)
 63             array[i] = array[i/2];
 64         array[i] = key;
 65     }
 66 }
 67 
 68 template<typename Comparable>
 69 void minHeap<Comparable>::increaseKey(int i,Comparable key)
 70 {
 71     if (key<array[i])
 72         cout << "new key is smaller than current key!" << endl;
 73     else
 74     {
 75         array[i] = key;
 76         minHeapify(i);
 77     }
 78 }
 79 
 80 template<typename Comparable>
 81 void minHeap<Comparable>::insert(const Comparable& key)
 82 {
 83     if(heapsize == array.size()-1)
 84         array.resize(array.size()*2);
 85     int hole = ++heapsize;
 86     for(; hole>1 && key<array[hole/2]; hole /=2) //向上過濾篩選
 87         array[hole] = array[hole/2];
 88     array[hole] = key;
 89 }
 90 
 91 template<typename Comparable>
 92 void minHeap<Comparable>::minHeapify(int hole) //向下過濾篩選
 93 {
 94     Comparable tmp = array[hole];
 95     for (int child = 2*hole; child <= heapsize; child *= 2)
 96     {
 97         if (child<heapsize && array[child] > array[child+1])
 98             ++child;
 99         if (tmp < array[child])
100             break;
101         array[hole] = array[child];
102         hole = child;
103     }
104     array[hole] = tmp;
105 }
106 
107 template<typename Comparable>
108 void minHeap<Comparable>::build_heap() //建堆
109 {
110     for (int i = heapsize/2; i>0; --i) //從下往上篩選
111         minHeapify(i);
112 }
113 
114 
115 template<typename Comparable>
116 void minHeap<Comparable>::remove(int p) //刪除位置p處的元素
117 {
118     array[p] = array[heapsize];
119     --heapsize;
120     Comparable key = array[p];
121     if (key>array[p/2]) //向下篩選
122         minHeapify(p);
123     else //向上篩選
124         for (; p>1,array[p/2]>key; p /=2)
125             array[p] = array[p/2];
126         array[p] = key;
127 }
128 
129 template<typename Comparable> // 構造函數之一
130 minHeap<Comparable>::minHeap(int campacity)
131 :    heapsize(campacity)
132 {
133     array.resize(campacity+10);
134 }
135 
136 template<typename Comparable> //構造函數之二
137 minHeap<Comparable>::minHeap(const vector<Comparable>& items)
138 :array(items.size()+10), heapsize(items.size())
139 {
140     for (int i = 0; i<items.size(); ++i)
141         array[i+1] = items[i];
142     build_heap();
143 }
144 
145 template<typename Comparable> //判斷堆是否為空
146 bool minHeap<Comparable>::isEmpty() const
147 {
148     if (0 == heapsize)
149         return true;
150     return false;
151 }
152 
153 
154 ////
155 template<typename Comparable>
156 void dumpContents(const string& msg, minHeap<Comparable>& pq)
157 {
158     cout << msg << ":" << endl;
159     while (!pq.isEmpty())
160     {
161         cout << pq.extractMin() << endl;
162     }
163 }
164 
165 int main()
166 {
167     //測試一
168     /*minHeap<int> minPQ;
169     minPQ.insert(4);
170     minPQ.insert(3);
171     minPQ.insert(2);
172     minPQ.insert(6);
173     minPQ.insert(1);
174     minPQ.increaseKey(4,20);
175     minPQ.decreaseKey(3,0);
176     minPQ.remove(5);
177     dumpContents("minPQ",minPQ);*/
178     
179     //測試二
180     vector<int> a;
181     a.push_back(10);
182     a.push_back(9);
183     a.push_back(7);
184     a.push_back(6);
185     a.push_back(5);
186     a.push_back(4);
187     minHeap<int> minpQ(a);
188     dumpContents("minPQ",minpQ);
189     return 0;
190 }

?

轉載于:https://www.cnblogs.com/lyfruit/archive/2012/12/29/2839311.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/376960.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/376960.shtml
英文地址,請注明出處:http://en.pswp.cn/news/376960.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

非常好的在網頁中顯示pdf的方法

今天有一需求&#xff0c;要在網頁中顯示pdf&#xff0c;于是立馬開始搜索解決方案&#xff0c;無意中發現一個非常好的解決方法&#xff0c;詳見http://blogs.adobe.com/pdfdevjunkie/web_designers_guide。 其實就光看這個網站也足夠了&#xff0c;http://www.pdfobject.com/…

Redis字典實現、Hash鍵沖突以及漸進式rehash

本筆記參考《Redis設計與實現》 P24~ 37 目錄Redis字典實現哈希表節點結構哈希表結構字典哈希算法解決hash沖突rehash漸進式hashRedis字典實現 哈希表節點結構 typedef struct dictEntry {// 鍵void *key;// 值 : 可以是一個指針&#xff0c;或者是一個uint64/int64 的整數un…

Java線程類void setContextClassLoader(ClassLoader loader)方法,帶示例

線程類void setContextClassLoader(ClassLoader loader) (Thread Class void setContextClassLoader(ClassLoader loader)) This method is available in package java.lang.Thread.setContextClassLoader(ClassLoader loader). 軟件包java.lang.Thread.setContextClassLoader(…

JPA概要

本文最新版已更新至&#xff1a;http://thinkinside.tk/2012/12/30/JPA.html JPA定義了Java ORM及實體操作API的標準。本文摘錄了JPA的一些關鍵信息以備查閱。 如果有hibernate的基礎&#xff0c;通過本文也可以快速掌握JPA的基本概念及使用。 Table of Contents 1 JPA概述2 實…

如何配置能讓fiddler抓去https的請求?

1、打開fiddler&#xff0c;>>Tools>>Fiddler Options&#xff0c; 打開如圖所示的HTTPS配置項&#xff1a;點擊Export Rppt Certifica to Desktop :桌面上多了一個證書&#xff1a;下面就是將證書導入&#xff1a;點擊開始-運行&#xff0c;輸入&#xff1a;mmc,…

Redis對象的refcount與lru屬性(內存回收、對象共享、空轉時長)

本筆記參考《Redis設計與實現》 P84~P88 內存回收 Redis在對象系統中使用reference counting技術實現了內存回收機制。程序可以通過跟蹤對象的引用計數信息&#xff0c;在適當的時候自動釋放對象并進行內存回收。 typedef struct redisObject {// ...// 引用計數int refcoun…

【閑聊】Baidu Map,excellent !!!Diaoyv island is China 's

【釣魚島】釣魚島是中國的&#xff01;Diaoyu Islands are Chinas! 釣魚島は中國のアール! ————————————youngLaker轉載于:https://www.cnblogs.com/younglaker/archive/2012/12/31/2840190.html

08:vigenère密碼_密碼技術:Vigenére密碼,Playfair密碼,Hill密碼

08:vigenre密碼1)Vigenre密碼 (1) Vigenre Cipher) This technique is an example of Polyalphabetic Substitution technique which uses 26 Caesar ciphers make up the mono-alphabetic substitution rules which follow a count shifting mechanism from 0 to 25. That is,…

Redis的RDB文件與AOF文件

本筆記參考《Redis設計與實現》 P118 ~ P150 RDB文件 1、RDB文件用于保存和還原Redis服務器所有數據庫中的所有鍵值對數據 2、SAVE命令由服務器進程直接執行保存操作&#xff0c;該命令會阻塞服務器 3、BGSAVE命令由子進程執行保存操作&#xff0c;不會阻塞服務器 注意此時服…

eclipse擴容

eclipse擴容 -vmD:/jdk-6u17-windows-i586/jdk1.6.0_17/bin/javaw.exe-startupplugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar-nlen_US--launcher.libraryplugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20120913-144807-productorg.eclipse…

node oauth2驗證_如何設置和使用護照OAuth Facebook身份驗證(第2部分)| Node.js

node oauth2驗證In my last article (How to set up and use passport OAuth Facebook Authentication (Section 1) | Node.js), we looked at another form of authentication called the OAuth authentication which involves sign in or signup using social media. 在我的上…

Python and Microsoft Word

國外網站看到的文章&#xff1a;Accessing Microsoft Word with Python follows the same syntax that we used for Excel. Let’s take a quick look at how to access Word.from time import sleep import win32com.client as win32RANGE range(3, 8)def word():word win32…

東哥讀書小記 之 《一個廣告人的自白》

掰著指頭一算&#xff0c;端午假期確實完成不少事情&#xff0c;過的太尼瑪充實鳥&#xff1a;去健身房2小時&#xff0c;且老夫的平板支撐終于能堅持超過1分鐘&#xff0c;普大喜奔有木有&#xff1b;給合租的室友買蛋糕過了個生日&#xff1b;去 去哪兒 參加W3ctech的技術交流…

Redis的文件事件與時間事件處理

目錄文件事件處理事件類型客戶端和服務端的通信過程時間事件處理執行器執行周期性事件作用事件的調度與執行文件事件處理 Redis基于Reactor模式開發了文件事件處理器。文件事件處理器以單線程方式運行&#xff0c;通過IO多路復用程序監聽多個套接字&#xff0c;實現了高性能網…

fisher-yates_使用Fisher-Yates隨機播放算法以O(n)時間隨機播放給定數組

fisher-yatesExample: 例&#xff1a; Say the input array is [1, 2 3, 4, 5 6, 7]After reshuffling it can be anything like[4, 3, 7, 2, 1, 5, 1]Our goal is that the reshuffling should be as random as possible. 我們的目標是&#xff0c;改組應盡可能地隨機。 The…

[分享]一些在 WPF/Silverlight 中應用 MVVM 模式時可能會有點用途的代碼

想來這個博客也已經有很久沒更新過了&#xff0c;新年新氣象&#xff0c;現在就開始寫新內容吧。 最初的起因 在最近的幾個月中我做的開發總是要跟 XAML 打交道&#xff0c;也就是 WPF 啊&#xff0c;Silverlight 啊&#xff0c;WF 啊這些。 在進行 WPF 和 Silverlight 開發的…

手機調用系統的拍照和裁剪功能,假設界面有輸入框EditText,在一些手機會出現點擊EditText會彈出輸入法,卻不能輸入的情況。...

1、拍照裁剪后 點擊EditText會彈出輸入法&#xff0c;卻不能輸入。可是點擊點一EdtiText就能夠輸入了&#xff0c;所以我就寫了一個看不見的EdtiText&#xff0c;切換焦點&#xff0c;這樣就攻克了這個奇怪的這問題&#xff0c;應該是android內部的問題。 這是網絡一個牛人留下…

Redis一個命令請求從發送到完成的步驟以及初始化服務器步驟

一個命令請求從發送到完成的步驟 如下&#xff1a; 1、客戶端將命令請求發送給服務器 當用戶在客戶端中鍵入一個命令請求時&#xff0c;客戶端會將這個命令請求轉換成協議格式&#xff0c;然后通過連接到服務器的套接字&#xff0c;將協議格式的命令請求發送給服務器。 2、服…

c打印行號和函數_使用C中的函數名稱,行號從任何函數打印錯誤消息

c打印行號和函數Sometimes, it is necessary to print some message on logic failure or anytime with the function name and line number, so that program can be debugged and fixed the issue. 有時&#xff0c;有必要在邏輯故障時或在任何時候使用功能名稱和行??號打印…

Linux SPI框架

水平有限&#xff0c;描述不當之處還請指出&#xff0c;轉載請注明出處http://blog.csdn.net/vanbreaker/article/details/7733476 Linux的SPI子系統采用主機驅動和外設驅動分離的思想&#xff0c;首先主機SPI控制器是一種平臺設備&#xff0c;因此它以platform的方式注冊進內…