编辑代码

public class Main {
	    public static void main(String[] args) {
        int[] arr = {4,6,2};
	        heap(arr);
	    }

	    //向上元素比较
	    public static void heap(int[] arr){
	        int[] heap = new int[arr.length+1];
	        for(int i=1;i<heap.length;i++){
            heap[i] = arr[i-1];
	        }
	
	        //堆化
	        for(int i=heap.length/2;i>0;i--){
	            heapfy(heap,heap.length,i);
        }
	
	        //顶底交换,然后 进行堆化
	        for(int i=heap.length-1;i>1;i--){
	            swap(heap,i,1);
	            heapfy(heap,i,1);
	        }
	
	        for(int i=1;i<heap.length;i++){
	            System.out.print(heap[i]+" ");
	        }
        }
	
    //向下比较
	    public static void heapfy(int[] heap,int len,int n){
        while(n<=(len-1)/2){
	            //子节点最大的
	            int temp = n*2;
            if(n*2+1<len) temp = heap[n*2]>heap[(n*2+1)]?(n*2):(n*2+1);
	            if(heap[n]>heap[temp]){
	                break;
            }
	            swap(heap,n,temp);
	            n = temp;
	        }
        }

	    public static void swap(int[] heap,int n,int m){
	        int temp = heap[n];
	        heap[n] = heap[m];
            heap[m] = temp;
	    }
}