堆排序算法

来源:互联网 发布:海量数据排序 编辑:程序博客网 时间:2024/06/06 03:47
public class HeapSort {    private static final int SIZE = 10; // 数组大小常量    /**     * 堆排序算法     *      * 平均时间复杂度——O(n*log^n)      * 最坏时间复杂度——O(n*log^n)     *      * @param a:待排序数组     * @param n:数组大小     *      */    public static void heapSort(int a[], int n) {        int i, j, k;        int t;      // 临时交换变量        // 将a[0,n-1]建成大根堆        for (i = n / 2 - 1; i >= 0; i--) {            // 第i个结点有右子树            while (2 * i + 1 < n) {                j = 2 * i + 1;                // 左子树小于右子树,则需要比较右子树,序号增加1,指向右子树                if ((j + 1) < n) {                    if (a[j] < a[j + 1]) j++;                }                // 比较i与j为序号的数据                if (a[i] < a[j]) {                    t = a[i]; // 交换数据                    a[i] = a[j];                    a[j] = t;                    i = j; // 堆被破坏,需要重新调整                // 比较左右子结点均大则堆未破坏,不再需要调整                } else {                    break;                }            }        }        // 输出构成的堆        System.out.print("原数据构成的堆:");        for (int h = 0; h < n; h++) {            System.out.print(" " + a[h]); // 输出        }        System.out.println();        for (i = n - 1; i > 0; i--) {            t = a[0]; // 与第i个记录交换            a[0] = a[i];            a[i] = t;            k = 0;            // 第i个结点有右子树            while (2 * k + 1 < i) {                j = 2 * k + 1;                if ((j + 1) < i) {                    // 右左子树小于右子树,则需要比较右子树                    if (a[j] < a[j + 1]) {                        j++; // 序号增加1,指向右子树                    }                }                // 比较i与j为序号的数据                if (a[k] < a[j]) {                    t = a[k]; // 交换数据                    a[k] = a[j];                    a[j] = t;                    k = j; // 堆被破坏,需要重新调整                    // 比较左右子结点均大则堆未破坏,不再需要调整                } else {                    break;                }            }            System.out.print("第" + (n - i) + "步排序结果:"); // 输出每步排序的结果            for (int h = 0; h < n; h++) {                System.out.print(" " + a[h]); // 输出            }            System.out.println();        }    }    public static void main(String[] args) {        // 数组创建及其初始化        int[] shuzu = new int[SIZE];        for (int i = 0; i < SIZE; i++) {            shuzu[i] = (int) (100 + Math.random() * (100 + 1)); // (0, 1) * 101 = (0, 101)        }        // 输出排序前的数组        System.out.print("排序前的数组为:");         for (int i = 0; i < SIZE; i++) {            System.out.print(shuzu[i] + " ");        }        System.out.print("\n");        // 堆排序        HeapSort.heapSort(shuzu, SIZE);        // 输出排序后的数组        System.out.print("排序后的数组为:");        for (int i = 0; i < SIZE; i++) {            System.out.print(shuzu[i] + " ");         }    }}
原创粉丝点击