JAVA堆排序(HEAP-SORT)

public class HeapSort {
    public static void heapSort(int[] array) {
        if (null == array || array.length < 2) {
            return;
        }
        int index;
        for (int i = 0; i < array.length; i++) {
            index = array.length - i - 1;
            maxHeap(array, index);
            if (index != 0) {
                array[0] ^= array[index];
                array[index] ^= array[0];
                array[0] ^= array[index];
            }
        }
    }

    private static void maxHeap(int[] array, int lastIndex) {
        int k;
        int index = (lastIndex - 1) / 2;
        for (int i = index; i > -1; i--) {
            k = i;
            while (2 * k <= lastIndex - 1) {
                int biggerIndex = 2 * k + 1;
                if (biggerIndex < lastIndex && array[biggerIndex] < array[biggerIndex + 1]) {
                    biggerIndex++;
                }
                if (array[k] < array[biggerIndex]) {
                    array[k] ^= array[biggerIndex];
                    array[biggerIndex] ^= array[k];
                    array[k] ^= array[biggerIndex];
                    k = biggerIndex;
                } else {
                    break;
                }
            }
        }
    }
}

你可能感兴趣的:(JAVA堆排序(HEAP-SORT))