堆排序

    public static void sort(int[] arry){
        int size = arry.length ;
        for(int i = size/2 -1 ;i>=0;i--){
            heapify( arry,size , i);
        }
        for(int i = size-1 ;i>=0 ;i--){
            swap(arry,i,0);
            heapify( arry,i , 0);
        }
    }


    public static void  heapify(int[] arry,int n ,int i){
        int left = 2*i+1;
        int right= 2*i+2;
        int max = i ;
        if(left < n && arry[left] > arry[max]){
            max = left;
        }
        if(right < n && arry[right] > arry[max]){
            max = right;
        }
        if(max !=i) {
            swap(arry, max, i);
            heapify(arry, n, max);
        }
    }

    public  static void swap(int[] arry,int i ,int j){
        int temp = arry[i];
        arry[i]=arry[j];
        arry[j]=temp;
    }

 

posted @ 2020-08-27 00:29  沙漠里的小鱼  阅读(94)  评论(0编辑  收藏  举报