堆排序

堆排序

public static void heapSort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return;
        }
        for (int i = arr.length / 2; i >= 0; i--) {
            buildHeap(arr, i, arr.length);
        }
        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr, 0, i);
            buildHeap(arr, 0, i);
        }
    }
    private static void buildHeap(int[] arr, int i, int n) {
        int child;
        int father;
        for (father = arr[i]; leftChild(i) < n; i = child) {
            child = leftChild(i);
            if (child != n - 1 && arr[child] < arr[child + 1]) {
                child++;
            }
            if (father < arr[child]) {
                arr[i] = arr[child];
            } else {
                break;
            }
        }
        arr[i] = father;
    }
    private static int leftChild(int i) {
        return 2 * i + 1;
    }
    private static void swap(int[] arr, int index1, int index2) {
        int tmp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = tmp;
    }

你可能感兴趣的:(堆排序)