堆排序

    科技2023-10-26  84

    public static void createHeap(int[] arry){ for(int i = (arry.length-1-1)/2; i>=0 ;i--){ adjustDown(arry,i,arry.length); } } // 向下调整,变成大根堆 private static void adjustDown(int[] arry, int root, int length) { int parent = root; int child = 2*parent+1; while(child < length){ if(child+1 <length && arry[child] < arry[child +1]){ child++; } if(arry[child] > parent){ int tmp = arry[child]; arry[child] = arry[parent]; arry[parent] = tmp; parent = child; child = 2*parent + 1; }else{ break; } } } /*时间复杂度O(nlogn) 空间复杂度O(1) 稳定性:不稳定*/ public static void heapSort(int[] arry){ createHeap(arry); int end = arry.length-1; while(end > 0){ int tmp = arry[0]; arry[0] = arry[end]; arry[end] = tmp; adjustDown(arry,0,end); end--; } } public static void main(String[] args) { int[] arry = {12,5,9,34,6,8,33,56,89,0,7,4,22,55,7}; System.out.println(Arrays.toString(arry)); heapSort(arry); System.out.println(Arrays.toString(arry)); }
    Processed: 0.011, SQL: 8