算法-->堆排序

来源:互联网 发布:黑魂3最美捏脸数据 编辑:程序博客网 时间:2024/04/30 13:16

感觉写的不是很好,自己的思绪还是有点乱。

package 堆排序;public class DuiPai {    static final int SIZE = 10;    static void heapSort(int a[], int n) {        int i, j, h, 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;                if (j + 1 < n) {                    // 右左子树小于右字树,则需要比较右子树                    if (a[j] < a[j + 1])                         j++;// 序号增加1,指向右子树                    }                    // 比较i和j为序号的数据                    if (a[i] < a[j]) {                        // 交换数据                        t = a[i];                        a[i] = a[j];                        a[j] = t;                        // 此时堆被破坏了,需要重新调整                        i = j;                    } else {                        break;                    }                }            // 输出构成的堆            System.out.println("源数据构成的堆:");            for (h = 0; h < n; h++) {                System.out.print(" " + a[h]);// 输出            }            System.out.print("\n");            for (i = n - 1; i > 0; i--) {                t = a[0];// 与第i个记录进行交换                a[0] = a[i];                a[i] = t;                k = 0;                while (2 * k + 1 < i) {                    j = 2 * k + 1;                    if (j + 1 < i) {                        // 右左子树小于右字树,则需要比较右子树                        if (a[j] < a[j + 1]) {                            j++;// 序号增加1,指向右子树                        }                    }                    if (a[k] < a[j]) {                        // 交换数据                        t = a[k];                        a[k] = a[j];                        a[j] = t;                        // 此时比较左右子节点都大堆被破坏了,不再重新调整                        k = j;                    } else {                        break;                    }                }                // 输出构成的堆                System.out.println("第:" + (n + 1) + "步排序结果是");                for (h = 0; h < n; h++) {                    System.out.print(" " + a[h]);// 输出                }                System.out.print("\n");            }        }    }    public static void main(String[] args) {        DuiPai dd = new DuiPai();        int[] shuzu = new int[SIZE];        int i;        for (i = 0; i < SIZE; i++) {            shuzu[i] = (int) (100 + Math.random() * (100 + 1));        }        System.out.print("排序前的数组为:\n");        for (i = 0; i < SIZE; i++) {            System.out.print(shuzu[i] + " ");        }        System.out.print("\n");        heapSort(shuzu, SIZE);        System.out.print("排序后的数组为:\n");        for (i = 0; i < SIZE; i++) {            System.out.print(shuzu[i] + " ");        }    }}

这里写图片描述

原创粉丝点击