1. package lhz.algorithm.chapter.six; 
  2. /** 
  3.  * “构建堆”,《算法导论》6.3章节 Building a heap 
  4.  * 利用之前实现的<code>MaxHeapify</code>算法,构建max-heap。 
  5.  * 伪代码: 
  6.  * BUILD-MAX-HEAP(A) 
  7.  * 1 heap-size[A] ← length[A] 
  8.  * 2 for i ← ⌊length[A]/2⌋ downto 1 
  9.  * 3 do MAX-HEAPIFY(A, i) 
  10.  * @author lihzh(苦逼coder) 
  11. * 本文地址:http://mushiqianmeng.blog.51cto.com/3970029/737557
  12.  */ 
  13. public class BuildMaxHeap { 
  14.      
  15.     private static int[] input = new int[] { 4132169101487 }; 
  16.     private static int heapSize = input.length; 
  17.  
  18.     public static void main(String[] args) { 
  19.         buildMaxHeap(); 
  20.         //打印数组 
  21.         printArray(); 
  22.     } 
  23.      
  24.     /** 
  25.      * 构造max-heap 
  26.      * 复杂度:《算法导论》原文分析如下: 
  27.      * Each call to MAX-HEAPIFY costs O(lg n) time, and there are O(n) such calls.  
  28.      * Thus,the running time is O(n lg n).  
  29.      */ 
  30.     private static void buildMaxHeap() { 
  31.         //从树的深层逆序,构造max-heap,正好每次均可满足 
  32.         //MaxHeapify算法的前提,即所有子二叉树已经是max-heap 
  33.         for (int i = heapSize/2; i > 0; i--) { 
  34.             maxHeapify(input, i); 
  35.         } 
  36.     } 
  37.      
  38.     /** 
  39.      * MaxHeap,调整算法,前提是假设所有的子二叉树已经是max-heap。 
  40.      * 复杂度: 
  41.      * 因为:T (n) ≤ T(2n/3) + Θ(1) 
  42.      * 所以有:T (n) = O(lgn) 
  43.      * @param array 
  44.      * @param index 
  45.      */ 
  46.     private static void maxHeapify(int[] array, int index) { 
  47.         int l = index * 2
  48.         int r = l + 1
  49.         int largest; 
  50.         //如果左叶子节点索引小于堆大小,比较当前值和左叶子节点的值,取值大的索引值 
  51.         if (l <= heapSize && array[l-1] > array[index-1]) { 
  52.             largest = l; 
  53.         } else { 
  54.             largest = index; 
  55.         } 
  56.         //如果右叶子节点索引小于堆大小,比较右叶子节点和之前比较得出的较大值,取大的索引值 
  57.         if (r <= heapSize && array[r-1] > array[largest-1]) { 
  58.             largest = r; 
  59.         } 
  60.         //交换位置,并继续递归调用该方法调整位置。 
  61.         if (largest != index) { 
  62.             int temp = array[index-1]; 
  63.             array[index-1] = array[largest-1]; 
  64.             array[largest-1] = temp; 
  65.             maxHeapify(array,largest); 
  66.         } 
  67.     } 
  68.      
  69.     private static void printArray() { 
  70.         for (int i : input) { 
  71.             System.out.print(i + " "); 
  72.         } 
  73.     } 

 图示: