public class Heap{ public static void main(String[] args){ Heap h=new Heap(); int[] heap=new int[]{1,2,3,4,5,6,7,8,9}; h.buildMaxHeap(heap); for(int i=0;i<heap.length;i++){ System.out.print(heap[i]+" "); } } public void buildMaxHeap(int[] heap){ for(int i=heap.length-1;i>=0;i--){ maxHeap(heap,i,heap.length); } } public void maxHeap(int[] heap,int index,int len){ int left=(index<<1)+1; int right=(index<<1)+2; int largest=index; if(left<len&&heap[left]>heap[largest]){ largest=left; } if(right<len&&heap[right]>heap[largest]){ largest=right; } if(largest!=index){ swap(heap,largest,index); maxHeap(heap,largest,len); } } public void swap(int[] heap,int left,int right){ int tmp=heap[left]; heap[left]=heap[right]; heap[right]=tmp; } }