1//O(nlogn)
public class BuildMaxHeap {
2
3 private static int[] input = new int[] { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 };
4 private static int heapSize = input.length;
5
6 public static void buildMaxHeap(){
7 for(int i=heapSize/2;i>0;i--){
8 maxHeapify(input, i);
9 }
10 }
11
12 public static void maxHeapify(int[] a,int index){
13 int l=index*2;
14 int r=l+1;
15 int largest;
16 if(l<=heapSize && a[l-1]>a[index-1]){
17 largest=l;
18 }
19 else{
20 largest=index;
21 }
22 if(r<=heapSize && a[r-1]>a[largest-1]){
23 largest=r;
24 }
25 if(largest != index){
26 int temp=a[index-1];
27 a[index-1]=a[largest-1];
28 a[largest-1]=temp;
29 maxHeapify(a,largest);
30 }
31
32 }
33
34 public static void printArray(int[] a){
35 for(int i = 0;i < a.length;i++){
36 System.out.print(a[i]+" ");
37 }
38 }
39
40 public static void main(String[] args) {
41 // TODO Auto-generated method stub
42 buildMaxHeap();
43 printArray(input);
44 }
45
46 }