Java之堆排序

    xiaoxiao2022-07-02  119

    直接上传代码

    public class Sort { public static void main(String[] args) { int[] arr = new int[]{8,7,6,5,4,3,2,1}; HeapSort(arr, arr.length); for(Object obj : arr){ System.out.println(obj); } } public static void AdjustDown(int[] array, int size, int root){ int left; int right; int maxchild; while (true){ left = 2*root+1; right = 2*root+2; if(left>=size){ return; } maxchild = left; if (right<size&&array[right]>array[left]){ maxchild = right; } if (array[root] >= array[maxchild]){ return; } int tmp = array[root]; array[root] = array[maxchild]; array[maxchild] = tmp; root = maxchild; } } public static void HeapSort(int[] array, int size){ for(int i = (size-2)/2; i>=0; i--){ AdjustDown(array,size, i); } for (int j = 0; j<size-1 ; j++){ int tmp = array[0]; array[0] = array[size-1-j]; array[size-1-j] = tmp; AdjustDown(array,size-j-1, 0); } } }
    最新回复(0)