日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

二叉堆(最小堆)(数据结构与算法分析的代码实现)

發布時間:2025/3/15 编程问答 11 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二叉堆(最小堆)(数据结构与算法分析的代码实现) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

“堆是一棵被完全填滿的二叉樹,可能的例外是在底層,底層上的元素從左到右填入。這樣的樹稱為完全二叉樹”

“因為完全二叉樹很有規律,所以可以用一個數組表示而不需要使用鏈”

上面兩句是摘自《數據結構與算法分析》

書中代碼的上濾和下濾的實現比算法導論的好,算法導論通過遞歸,每一次都交換不合適的節點,書本的代碼則是通過循環找到節點正在要移動到的位置。

參考算法導論的代碼:http://www.cnblogs.com/alan-forever/archive/2012/09/26/2704860.html

算法導論的是堆排序的代碼,不過堆的性質都有的。

下面的代碼是最小堆的,而且是一個類模板。

View Code 1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 5 template <typename Comparable> 6 class BinaryHeap 7 { 8 public: 9 explicit BinaryHeap( int capacity = 100 ) : array( capacity + 10 ) 10 { 11 currentSize = 0; 12 } 13 14 explicit BinaryHeap( const vector<Comparable> & item ) : array( item.size() + 10 ), currentSize( item.size() ) 15 { 16 for(int i = 0; i < item.size(); ++i) 17 array[i+1] = item[i]; 18 buildHeap(); 19 } 20 21 bool isEmpty() const 22 { 23 return currentSize == 0; 24 } 25 26 const Comparable & finMin( ) const 27 { 28 return array[1]; 29 } 30 31 void insert( const Comparable & x) 32 { 33 if(currentSize == array.size() - 1) 34 array.resize( array.size() * 2); 35 36 int hole = ++currentSize; 37 for(; hole > 1 && x < array[hole / 2]; hole /= 2) 38 array[hole] = array[hole / 2]; 39 array[hole] = x; 40 } 41 42 void deleteMin() 43 { 44 array[1] = array[currentSize--]; 45 percolateDowm( 1 ); 46 } 47 48 void deleteMin(Comparable & Min) 49 { 50 Min = array[1]; 51 deleteMin(); 52 } 53 54 void makeEmpty() 55 { 56 delete array[currentSize]; 57 currentSize = 0; 58 } 59 60 void print( ) 61 { 62 for(int i = 1; i <= currentSize; ++i) 63 cout << array[i] << " "; 64 cout << endl; 65 } 66 67 private: 68 int currentSize; 69 vector<Comparable> array; 70 71 void buildHeap() 72 { 73 for(int i = currentSize / 2; i > 0; i--) 74 percolateDowm( i ); 75 } 76 77 void percolateDowm( int hole ) 78 { 79 int child; 80 Comparable temp = array[hole]; 81 82 for(; hole * 2 <= currentSize; hole = child) 83 { 84 child = hole * 2; 85 if(child != currentSize && array[child + 1] < array[child]) 86 child++; 87 if(array[child] < temp) 88 array[hole] = array[child]; 89 else 90 break; 91 } 92 array[hole] = temp; 93 } 94 }; 95 96 int main() 97 { 98 vector<int> a; 99 int m; 100 for(int i = 0; i < 10; ++i) 101 { 102 cin >> m; 103 a.push_back( m ); 104 } 105 BinaryHeap<int> minHeap( a ); 106 cin >> m; 107 minHeap.insert( m ); 108 minHeap.deleteMin(); 109 minHeap.print(); 110 return 0; 111 }

?

轉載于:https://www.cnblogs.com/alan-forever/archive/2012/12/11/2813417.html

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的二叉堆(最小堆)(数据结构与算法分析的代码实现)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。