1. package lhz.algorithm.chapter.six; 
  2.  
  3. /** 
  4.  * MAX-HEAPIFY,《算法导论》第六章  
  5.  * 算法导论原文: 
  6.  * MAX-HEAPIFY is an important subroutine for manipulating max-heaps. Its inputs are an 
  7.  * array A and an index i into the array. When MAX-HEAPIFY is called, it is assumed that the 
  8.  * binary trees rooted at LEFT(i) and RIGHT(i) are max-heaps, but that A[i] may be smaller than 
  9.  * its children, thus violating the max-heap property. The function of MAX-HEAPIFY is to let 
  10.  * the value at A[i] "float down" in the max-heap so that the subtree rooted at index i becomes a 
  11.  * max-heap. 
  12.  * 伪代码: 
  13.  * MAX-HEAPIFY(A, i)  
  14.  * 1 l ← LEFT(i)  
  15.  * 2 r ← RIGHT(i)  
  16.  * 3 if l ≤ heap-size[A] and A[l] > A[i]  
  17.  * 4 then largest ← l  
  18.  * 5 else largest ← i  
  19.  * 6 if r ≤ heap-size[A] and A[r] > A[largest]  
  20.  * 7 then largest ← r  
  21.  * 8 if largest ≠ i  
  22.  * 9 then exchange A[i] ↔ A[largest] 10 MAX-HEAPIFY(A, largest) 
  23.  * @author lihzh(苦逼coder) 
  24. * 本文地址:http://mushiqianmeng.blog.51cto.com/3970029/736717
  25.  */ 
  26. public class MaxHeapify { 
  27.  
  28.     private static int[] input = new int[] { 1641014793281 }; 
  29.     private static int heapSize = input.length; 
  30.  
  31.     public static void main(String[] args) { 
  32.         maxHeapify(input, 2);//此处,2对于二叉树中的索引值,对应数组中的4 
  33.         //打印数组 
  34.         printArray(); 
  35.     } 
  36.      
  37.     /** 
  38.      * MaxHeap,调整算法,前提是假设所有的子二叉树已经是max-heap。 
  39.      * 复杂度: 
  40.      * 因为:T (n) ≤ T(2n/3) + Θ(1) 
  41.      * 所以有:  * T (n) = O(lgn) 
  42.      * @param array 
  43.      * @param index 
  44.      */ 
  45.     private static void maxHeapify(int[] array, int index) { 
  46.         int l = index * 2
  47.         int r = l + 1
  48.         int largest; 
  49.         //如果左叶子节点索引小于堆大小,比较当前值和左叶子节点的值,取值大的索引值 
  50.         if (l <= heapSize && array[l-1] > array[index-1]) { 
  51.             largest = l; 
  52.         } else { 
  53.             largest = index; 
  54.         } 
  55.         //如果右叶子节点索引小于堆大小,比较右叶子节点和之前比较得出的较大值,取大的索引值 
  56.         if (r <= heapSize && array[r-1] > array[largest-1]) { 
  57.             largest = r; 
  58.         } 
  59.         //交换位置,并继续递归调用该方法调整位置。 
  60.         if (largest != index) { 
  61.             int temp = array[index-1]; 
  62.             array[index-1] = array[largest-1]; 
  63.             array[largest-1] = temp; 
  64.             maxHeapify(array,largest); 
  65.         } 
  66.     } 
  67.      
  68.     private static void printArray() { 
  69.         for (int i : input) { 
  70.             System.out.print(i + " "); 
  71.         } 
  72.     } 
  73.  
图示: