java 堆排序实现


public class Main {

	public static void adjustTree(int[] a, int i, int len) {
        int temp, j;
        temp = a[i];
   // 沿关键字较大的孩子结点向下筛选
        for (j = 2 * i; j < len; j *= 2) {
            if (j < 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 / 2 - 1; i >= 0; i--) {
            adjustTree(a, i, a.length - 1);
        }

    // 将堆顶记录和当前未经排序子序列的最后一个记录交换
        for (i = a.length - 1; i >= 0; i--) {
            int temp = a[0];
            a[0] = a[i];
            a[i] = temp;
            adjustTree(a, 0, i - 1);// 将a中前i-1个记录重新调整为大顶堆
        }
    }

    public static void main(String[] args) {
        int a[] = {7,6,5,4,3,2,1};
        heapSort(a);
        for(int i : a)
            System.out.println(i);
    }


}

猜你喜欢

转载自blog.csdn.net/qq_39094614/article/details/82561289