---
title: "彻底弄懂最大堆的四种操作(图解+程序)（JAVA）"
author: "speed847"
date: "2013-11-07T22:44:47Z"
tags: []
categories: ["企业架构"]
slug: "java"
draft: false
lastmod: "2013-11-07T22:44:47Z"
id: 1972857
url: "https://speed847.iteye.com/blog/1972857"
---

[http://128kj.iteye.com/blog/1728555](http://128kj.iteye.com/blog/1728555)

堆有最大堆和最小堆之分，最大堆就是每个节点的值都&gt;=其左右孩子（如果有的话）值的完全二叉树。最小堆便是每个节点的值都&lt;=其左右孩子值的完全二叉树。 

  设有n个元素的序列{k1,k2,...,kn},当且仅当满足下列关系时,称之为堆。   
![](http://dl.iteye.com/upload/attachment/0076/7485/7103103d-0611-3b1c-8597-2ae98cc3da68.jpg) 

堆的三种基本操作(以下以最大堆为例)：   
⑴最大堆的插入   

    由于需要维持完全二叉树的形态，需要先将要插入的结点x放在最底层的最右边，插入后满 足完全二叉树的特点；   
  然后把x依次向上调整到合适位置满足堆的性质,例如下图中插入80,先将80放在最后,然后两次上浮到合适位置.   
  时间：O(logn)。  “结点上浮”   
![](http://dl.iteye.com/upload/attachment/0076/7487/ce44cd81-7e29-3fd2-af8f-9326d13523e6.jpg) 

程序实现: 

Java代码  [![收藏代码](http://128kj.iteye.com/images/icon_star.png)]()

01. //向最大堆中插入元素, heap:存放堆元素的数组
02. public static void insert(List&lt;Integer&gt; heap, int value) {
03. //在数组的尾部添加
04. if(heap.size()==0)
05. heap.add(0);//数组下标为0的位置不放元素
06. heap.add(value);
07. //开始上升操作
08. // heapUp2(heap, heap.size() - 1);
09. heapUp(heap, heap.size() - 1);
10. }
11. //上升，让插入的数和父节点的数值比较，当大于父节点的时候就和父节点的值相交换
12. public static void heapUp(List&lt;Integer&gt; heap, int index) {
13. //注意由于数值是从下标为1开始，当index = 1的时候，已经是根节点了
14. if (index &gt; 1) {
15. //求出父亲的节点
16. int parent = index / 2;
17. //获取相应位置的数值
18. int parentValue = (Integer) heap.get(parent);
19. int indexValue = (Integer) heap.get(index);
20. //如果父亲节点比index的数值小，就交换二者的数值
21. if (parentValue &lt; indexValue) {
22. //交换数值
23. swap(heap, parent, index);
24. //递归调用
25. heapUp(heap, parent);
26. }
27. }
28. }

⑵删除   
   操作原理是：当删除节点的数值时，原来的位置就会出现一个孔,填充这个孔的方法就是，   
把最后的叶子的值赋给该孔并下调到合适位置，最后把该叶子删除。   
    
如图中要删除72,先用堆中最后一个元素来35替换72,再将35下沉到合适位置,最后将叶子节点删除。   
　　“结点下沉” 

![](http://dl.iteye.com/upload/attachment/0076/7493/7a8796eb-e4f7-3268-a9a3-8d870f853d59.jpg) 

Java代码  [![收藏代码](http://128kj.iteye.com/images/icon_star.png)]()

01. 程序:
02. /\**
03. * 删除堆中位置是index处的节点
04. * 操作原理是：当删除节点的数值时，原来的位置就会出现一个孔
05. * 填充这个孔的方法就是，把最后的叶子的值赋给该孔，最后把该叶子删除
06. * @param heap
07. \*/
08. public static void delete(List&lt;Integer&gt; heap,int index) {
09. //把最后的一个叶子的数值赋值给index位置
10. heap.set(index, heap.get(heap.size() - 1));
11. //下沉操作
12. //heapDown2(heap, index);
13. heapDown(heap, index);
14. //把最后一个位置的数字删除
15. heap.remove(heap.size() - 1);
16. }
17. /\**
18. * 递归实现
19. * 删除堆中一个数据的时候，根据堆的性质，应该把相应的位置下移，才能保持住堆性质不变
20. * @param heap 保持堆元素的数组
21. * @param index 被删除的那个节点的位置
22. \*/
23. public static void heapDown(List&lt;Integer&gt; heap, int index) {
24. //因为第一个位置存储的是空值，不在考虑之内
25. int n = heap.size() - 2;
26. //记录最大的那个儿子节点的位置
27. int child = -1;
28. //2\*index&gt;n说明该节点没有左右儿子节点了，那么就返回
29. if (2 * index &gt; n) {
30. return;
31. } //如果左右儿子都存在
32. else if (2 * index &lt; n) {
33. //定义左儿子节点
34. child = 2 * index;
35. //如果左儿子小于右儿子的数值，取右儿子的下标
36. if ((Integer) heap.get(child) &lt; (Integer) heap.get(child + 1)) {
37. child++;
38. }
39. }//如果只有一个儿子（左儿子节点）
40. else if (2 * index == n) {
41. child = 2 * index;
42. }
43. if ((Integer) heap.get(child) &gt; (Integer) heap.get(index)) {
44. //交换堆中的child，和index位置的值
45. swap(heap, child, index);
46. //完成交换后递归调用，继续下降
47. heapDown(heap, child);
48. }
49. }

⑶初始化   
方法1：插入法：   
  从空堆开始，依次插入每一个结点，直到所有的结点全部插入到堆为止。   
  时间：O(n\*log(n))   
  方法2：调整法：   
    序列对应一个完全二叉树；从最后一个分支结点（n div 2）开始，到根（1）为止，依次对每个分支结点进行调整（下沉），以便形成以每个分支结点为根的堆，当最后对树根结点进行调整后，整个树就变成了一个堆。   
  时间：O(n)   
对如图的序列,要使其成为堆,我们从最后一个分支结点(10/2),其值为72开始,依次对每个分支节点53,18,36 45进行调整(下沉).   
![](http://dl.iteye.com/upload/attachment/0076/7499/127c901b-80b9-35e3-b255-8bcf3a8cfc27.jpg)   
![](http://dl.iteye.com/upload/attachment/0076/7497/d8cfe5ac-e0f7-37eb-8b16-cb6afbc23e51.jpg)   
![](http://dl.iteye.com/upload/attachment/0076/7495/b938d263-1bc3-3956-8b3f-1c210a25eb63.jpg) 

Java代码  [![收藏代码](http://128kj.iteye.com/images/icon_star.png)]()

01. 程序:
02. /\*根据树的性质建堆，树节点前一半一定是分支节点，即有孩子的，所以我们从这里开始调整出初始堆\*/
03. public static void adjust(List&lt;Integer&gt; heap){
04. for (int i = heap.size() / 2; i &gt; 0; i--)
05. adjust(heap,i, heap.size()-1);
06. System.out.println("=================================================");
07. System.out.println("调整后的初始堆：");
08. print(heap);
09. }
10. /\**
11. * 调整堆，使其满足堆得定义
12. * @param i
13. * @param n
14. \*/
15. public static void adjust(List&lt;Integer&gt; heap,int i, int n) {
16. int child;
17. for (; i &lt;= n / 2; ) {
18. child = i * 2;
19. if(child+1&lt;=n&&heap.get(child)&lt;heap.get(child+1))
20. child+=1;/\*使child指向值较大的孩子\*/
21. if(heap.get(i)&lt; heap.get(child)){
22. swap(heap,i, child);
23. /\*交换后，以child为根的子树不一定满足堆定义，所以从child处开始调整\*/
24. i = child;
25. }  else break;
26. }
27. }

(4)最大堆排序  

Java代码  [![收藏代码](http://128kj.iteye.com/images/icon_star.png)]()

1. //对一个最大堆heap排序
2. public static void heapSort(List&lt;Integer&gt; heap) {
3. for (int i = heap.size()-1; i &gt; 0; i--) {
4. /\*把根节点跟最后一个元素交换位置，调整剩下的n-1个节点，即可排好序\*/
5. swap(heap,1, i);
6. adjust(heap,1, i - 1);
7. }
8. }

(5)完整的代码 

Java代码  [![收藏代码](http://128kj.iteye.com/images/icon_star.png)]()

001. import java.util.\*;
002. /\**
003. \*实现的最大堆的插入和删除操作
004. * @author Arthur
005. \*/
006. public class Heap {
007. /\**
008. * 删除堆中位置是index处的值
009. * 操作原理是：当删除节点的数值时，原来的位置就会出现一个孔
010. * 填充这个孔的方法就是，把最后的叶子的值赋给该孔，最后把该叶子删除
011. * @param heap 一个最大堆
012. \*/
013. public static void delete(List&lt;Integer&gt; heap,int index) {
014. //把最后的一个叶子的数值赋值给index位置
015. heap.set(index, heap.get(heap.size() - 1));
016. //下沉操作
017. //heapDown2(heap, index);
018. heapDown(heap, index); //节点下沉
019. //把最后一个位置的数字删除
020. heap.remove(heap.size() - 1);
021. }
022. /\**
023. * 节点下沉递归实现
024. * 删除一个堆中一个数据的时候，根据堆的性质，应该把相应的位置下移，才能保持住堆性质不变
025. * @param heap 保持最大堆元素的数组
026. * @param index 被删除的那个节点的位置
027. \*/
028. public static void heapDown(List&lt;Integer&gt; heap, int index) {
029. //因为第一个位置存储的是空值，不在考虑之内
030. int n = heap.size() - 2;
031. //记录最大的那个儿子节点的位置
032. int child = -1;
033. //2\*index&gt;n说明该节点没有左右儿子节点了，那么就返回
034. if (2 * index &gt; n) {
035. return;
036. } //如果左右儿子都存在
037. else if (2 * index &lt; n) {
038. //定义左儿子节点
039. child = 2 * index;
040. //如果左儿子小于右儿子的数值，取右儿子的下标
041. if ((Integer) heap.get(child) &lt; (Integer) heap.get(child + 1)) {
042. child++;
043. }
044. }//如果只有一个儿子（左儿子节点）
045. else if (2 * index == n) {
046. child = 2 * index;
047. }
048. if ((Integer) heap.get(child) &gt; (Integer) heap.get(index)) {
049. //交换堆中的child，和index位置的值
050. swap(heap, child, index);
051. //完成交换后递归调用，继续下降
052. heapDown(heap, child);
053. }
054. }
055. //非递归实现
056. public static void heapDown2(List&lt;Integer&gt; heap, int index) {
057. int child = 0;//存储左儿子的位置
058. int temp = (Integer) heap.get(index);
059. int n = heap.size() - 2;
060. //如果有儿子的话
061. for (; 2 * index &lt;= n; index = child) {
062. //获取左儿子的位置
063. child = 2 * index;
064. //如果只有左儿子
065. if (child == n) {
066. child = 2 * index;
067. } //如果右儿子比左儿子的数值大
068. else if ((Integer) heap.get(child) &lt; (Integer) heap.get(child + 1)) {
069. child++;
070. }
071. //如果数值最大的儿子比temp的值大
072. if ((Integer) heap.get(child) &gt;temp) {
073. //交换堆中的child，和index位置的值
074. swap(heap, child, index);
075. } else {
076. break;
077. }
078. }
079. }
080. //打印链表
081. public static void print(List&lt;Integer&gt; list) {
082. for (int i = 1; i &lt; list.size(); i++) {
083. System.out.print(list.get(i) + " ");
084. }
085. System.out.println();
086. }
087. //把堆中的a,b位置的值互换
088. public static void swap(List&lt;Integer&gt; heap, int a, int b) {
089. //临时存储child位置的值
090. int temp = (Integer) heap.get(a);
091. //把index的值赋给child的位置
092. heap.set(a, heap.get(b));
093. //把原来的child位置的数值赋值给index位置
094. heap.set(b, temp);
095. }
096. //向最大堆中插入元素
097. public static void insert(List&lt;Integer&gt; heap, int value) {
098. //在数组的尾部添加要插入的元素
099. if(heap.size()==0)
100. heap.add(0);//数组下标为0的位置不放元素
101. heap.add(value);
102. //开始上升操作
103. // heapUp2(heap, heap.size() - 1);
104. heapUp(heap, heap.size() - 1);
105. }
106. //节点上浮，让插入的数和父节点的数值比较，当大于父节点的时候就和节点的值相交换
107. public static void heapUp(List&lt;Integer&gt; heap, int index) {
108. //注意由于数值是从小标为一开始，当index = 1的时候，已经是根节点了
109. if (index &gt; 1) {
110. //保存父亲的节点
111. int parent = index / 2;
112. //获取相应位置的数值
113. int parentValue = (Integer) heap.get(parent);
114. int indexValue = (Integer) heap.get(index);
115. //如果父亲节点比index的数值小，就交换二者的数值
116. if (parentValue &lt; indexValue) {
117. //交换数值
118. swap(heap, parent, index);
119. //递归调用
120. heapUp(heap, parent);
121. }
122. }
123. }
124. //非递归实现
125. public static void heapUp2(List&lt;Integer&gt; heap, int index) {
126. int parent = 0;
127. for (; index &gt; 1; index /= 2) {
128. //获取index的父节点的下标
129. parent = index / 2;
130. //获得父节点的值
131. int parentValue = (Integer) heap.get(parent);
132. //获得index位置的值
133. int indexValue = (Integer) heap.get(index);
134. //如果小于就交换
135. if (parentValue &lt; indexValue) {
136. swap(heap, parent, index);
137. }
138. }
139. }
140. /\*根据树的性质建堆，树节点前一半一定是分支节点，即有孩子的，所以我们从这里开始调整出初始堆\*/
141. public static void adjust(List&lt;Integer&gt; heap){
142. for (int i = heap.size() / 2; i &gt; 0; i--)
143. adjust(heap,i, heap.size()-1);
144. System.out.println("=================================================");
145. System.out.println("调整后的初始堆：");
146. print(heap);
147. }
148. /\**
149. * 调整堆，使其满足堆得定义
150. * @param i
151. * @param n
152. \*/
153. public static void adjust(List&lt;Integer&gt; heap,int i, int n) {
154. int child;
155. for (; i &lt;= n / 2; ) {
156. child = i * 2;
157. if(child+1&lt;=n&&heap.get(child)&lt;heap.get(child+1))
158. child+=1;/\*使child指向值较大的孩子\*/
159. if(heap.get(i)&lt; heap.get(child)){
160. swap(heap,i, child);
161. /\*交换后，以child为根的子树不一定满足堆定义，所以从child处开始调整\*/
162. i = child;
163. }  else break;
164. }
165. }
166. //对一个最大堆heap排序
167. public static void heapSort(List&lt;Integer&gt; heap) {
168. for (int i = heap.size()-1; i &gt; 0; i--) {
169. /\*把根节点跟最后一个元素交换位置，调整剩下的n-1个节点，即可排好序\*/
170. swap(heap,1, i);
171. adjust(heap,1, i - 1);
172. }
173. }
174. public static void main(String args\[]) {
175. List&lt;Integer&gt; array = new ArrayList&lt;Integer&gt;(Arrays.asList(null, 1, 2, 5, 10, 3, 7, 11, 15, 17, 20, 9, 15, 8, 16));
176. adjust(array);//调整使array成为最大堆
177. delete(array,8);//堆中删除下标是8的元素
178. System.out.println("删除后");
179. print(array);
180. insert(array, 99);//堆中插入
181. print(array);
182. heapSort(array);//排序
183. System.out.println("将堆排序后:");
184. print(array);
185. System.out.println("-------------------------");
186. List&lt;Integer&gt; array1=new ArrayList&lt;Integer&gt;();
187. insert(array1,0);
188. insert(array1, 1);insert(array1, 2);insert(array1, 5);
189. insert(array1, 10);insert(array1, 3);insert(array1, 7);
190. insert(array1, 11);insert(array1, 15); insert(array1, 17);
191. insert(array1, 20);insert(array1, 9);
192. insert(array1, 15);insert(array1, 8);insert(array1, 16);
193. print(array1);
194. System.out.println("==============================");
195. array=new ArrayList&lt;Integer&gt;(Arrays.asList(null,45,36,18,53,72,30,48,93,15,35));
196. adjust(array);
197. insert(array, 80);//堆中插入
198. print(array);
199. delete(array,2);//堆中删除80的元素
200. print(array);
201. delete(array,2);//堆中删除72的元素
202. print(array);
203. }
204. }

程序运行:   
D:\\java&gt;java   Heap   
\=================================================   
调整后的初始堆：   
20 17 16 15 9 15 11 1 10 3 2 7 8 5   
删除后   
20 17 16 15 9 15 11 5 10 3 2 7 8   
99 17 20 15 9 15 16 5 10 3 2 7 8 11   
将堆排序后:   
2 3 5 7 8 9 10 11 15 15 16 17 20 99   
\-------------------------   
20 17 16 10 15 9 15 0 5 2 11 1 7 3 8   
\==============================   
\=================================================   
调整后的初始堆：   
93 72 48 53 45 30 18 36 15 35   
93 80 48 53 72 30 18 36 15 35 45   
93 72 48 53 45 30 18 36 15 35   
93 53 48 36 45 30 18 35 15   
源码下载