最小堆实现代码

参考算法导论、数据结构相关书籍,写得最小堆实现的源代码如下:

  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.mzph.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的方式注册进内…