Java 大堆排序从0开始

来源:互联网 发布:创世数据网 编辑:程序博客网 时间:2024/06/08 11:02
public class HeapSortFrom0 {    /*                                51                     46                           20             18              -10             82        65         30      77     97       101     85     */    /**     * 构建大顶堆     */    public static void adjustHeap(int[] a, int i, int len) {        int temp;        temp = a[i];//最后一个节点的父节点        for (int j = 2 * i + 1; j <= len; j = 2 * j + 1) {// 沿关键字较大的孩子结点向下筛选            if (j + 1 <= len && a[j] < a[j + 1])                ++j; // j为关键字中较大记录的下标            if (temp >= a[j])                break;            a[i] = a[j];            i = j;            a[i] = temp;        }    }    public static void heapSort(int[] a) {        int i;        for (i = ((a.length - 1) - 1) / 2; i >= 0; i--) {// 构建一个大顶堆            adjustHeap(a, i, a.length - 1);        }        //System.out.println(Arrays.toString(a));        //System.exit(0);        for (i = a.length - 1; i > 0; i--) {// 将堆顶记录和当前未经排序子序列的最后一个记录交换            int temp = a[0];            a[0] = a[i];            a[i] = temp;            adjustHeap(a, 0, i - 1);// 将a中前i-1个记录重新调整为大顶堆        }    }    public static void main(String[] args) {        int a[] = {51, 46, 20, 18, -10, 82, 65, 30, 77, 97,101,85};        heapSort(a);        System.out.println(Arrays.toString(a));    }}