Java大顶堆实现堆排序

本文介绍了Java中如何运用大顶堆实现堆排序,详细解析了堆排序的时间复杂度,包括最好、最坏和平均情况,均为O(nlog2n)。此外,文章指出堆排序是不稳定的排序算法。内容还涉及对给定整型数进行从小到大排序的归并排序问题。
摘要由CSDN通过智能技术生成
堆排序

时间复杂度
最好情况:O(nlog2n)
最坏情况:O(nlog2n)
平均情况:O(nlog2n)
稳定性
稳定性:不稳定

问题: 给你n个无序的像m的整型数,请使用归并排序实现从小到大的顺序。(0 <= n <= 5 * 104,-1 * 105 <= m <= 1 * 105

public class HeadSort {
    public static void sort(int[] a) {
        headSort(a, a.length - 1);
    }

    private static void headSort(int[] a, int high) {
        for (int i = (high - 1) >> 1; i > 0; i--) {
            adjust(a, i, high);
        }
        for (int i = high; i > 0; i--) {
            int temp = a[0];
            a[0] = a[i];
            a[i] = temp;
            adjust(a, 0, i - 1);
        }
    }


    private static void adjust(int[] a, int curPeak, int high) {
        while (true) {
            int child = (curPeak << 1) + 1;
            if (child > high) {
                break;
            }
            if (child < high && a[child] < a[child + 1]) {
                child++;
            }
            if (a[child] > a[curPeak]) {
                int temp = a[curPeak];
                a[curPeak] = a[child];
                a[child] = temp;
                curPeak = child;
            } else {
                break;
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值