11package sort ;
22
33/*
4- 1、堆:堆本质上就是一棵完全二叉树,它的每一个节点都必须大于或者小于其子节点
5- 2、最大堆:每个节点都大于或者等于子树所有节点的堆称为最大堆
6- 最小堆:每个节点都小于或者等于子树所有节点的堆称为最小堆
4+ 1、堆:堆本质上就是一棵完全二叉树,它的每一个节点都必须大于等于或者小于等于其子节点
5+ 2、最大堆:每个节点都大于等于子树所有节点的堆称为最大堆
6+ 最小堆:每个节点都小于等于子树所有节点的堆称为最小堆
773、数组存储堆,节点的索引关系如下
88 索引角度:起始索引为0,某个节点在数组中的索引为i,则其(直接看索引,好记)
99 1)父节点索引:(i-1)/2
@@ -51,11 +51,13 @@ private void maxHeapify(int[] nums, int root) {
5151 // 索引从0开始
5252 int left = root * 2 + 1 , right = root * 2 + 2 ;
5353 // 如果有左孩子,且左孩子大于父节点,则将最大指针指向左孩子
54- if (left < n && nums [left ] > nums [maxIndex ])
54+ if (left < n && nums [left ] > nums [maxIndex ]) {
5555 maxIndex = left ;
56+ }
5657 // 如果有右孩子,且右孩子大于父节点和左孩子,则将最大指针指向右孩子
57- if (right < n && nums [right ] > nums [maxIndex ])
58+ if (right < n && nums [right ] > nums [maxIndex ]) {
5859 maxIndex = right ;
60+ }
5961 // 如果父节点不是最大值,则将父节点与最大值交换,并且递归调整与父节点交换的位置
6062 if (maxIndex != root ) {
6163 swap (nums , maxIndex , root );
@@ -73,8 +75,9 @@ public static void main(String[] args) {
7375 int [] nums = {1 , 4 , 6 , 2 , 3 , 8 , 7 , 5 , 9 };
7476 Heap heap = new Heap ();
7577 nums = heap .heapSort (nums );
76- for (int num : nums )
78+ for (int num : nums ) {
7779 System .out .println (num );
80+ }
7881 }
7982}
8083
@@ -99,10 +102,12 @@ public int[] heapSort(int[] nums) {
99102 private void maxHeapify (int [] nums , int root ) {
100103 int maxIndex = root ;
101104 int left = root * 2 + 1 , right = root * 2 + 2 ;
102- if (left < n && nums [left ] > nums [maxIndex ])
105+ if (left < n && nums [left ] > nums [maxIndex ]) {
103106 maxIndex = left ;
104- if (right < n && nums [right ] > nums [maxIndex ])
107+ }
108+ if (right < n && nums [right ] > nums [maxIndex ]) {
105109 maxIndex = right ;
110+ }
106111 if (maxIndex != root ) {
107112 swap (nums , maxIndex , root );
108113 maxHeapify (nums , maxIndex );
@@ -143,10 +148,12 @@ public int[] heapSort(int[] nums) {
143148 private void minHeapify (int [] nums , int root ) {
144149 int minIndex = root ;
145150 int left = root * 2 + 1 , right = root * 2 + 2 ;
146- if (left < n && nums [left ] < nums [minIndex ])
151+ if (left < n && nums [left ] < nums [minIndex ]) {
147152 minIndex = left ;
148- if (right < n && nums [right ] < nums [minIndex ])
153+ }
154+ if (right < n && nums [right ] < nums [minIndex ]) {
149155 minIndex = right ;
156+ }
150157 if (minIndex != root ) {
151158 swap (nums , minIndex , root );
152159 minHeapify (nums , minIndex );
0 commit comments