算法-堆排序及其应用

题目:堆排序 递增

思路:先构建大根堆,交换0位置和大根堆最后位置,大根堆size--,由于0位置值更新了,需要从o开始往下撸一遍,把0位置值放在正确位置

// 堆排序
    public static void heapSort(int[] arr) {
        if (arr == null || arr.length <= 0)
            return;
        // 在arr上构建大根堆
        buildHeap(arr);
        // 交换第一个和最后一个位置元素,小根堆长度--,同时更新小根堆
        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr, i, 0);
            down(arr, 0, i - 1);
        }
    }

    public static void buildHeap(int[] arr) {
        for (int i = arr.length - 1; i >= 0; i--) {
            // 将当前i位置元素往下怼到正确的位置
            down(arr, i, arr.length - 1);
        }
    }

    // end为可以访问到的位置
    public static void down(int[] arr, int index, int end) {
        int child = index * 2 + 1;
        int parent = index;
        while (child <= end) {
            child = child + 1 <= end && arr[child + 1] > arr[child] ? child + 1 : child;
            if (arr[parent] > arr[child]) {
                break;
            }
            swap(arr, parent, child);
            parent = child;
            child = parent * 2 + 1;
        }
    }

    public static void swap(int[] arr, int a, int b) {
        int tmp = arr[a];
        arr[a] = arr[b];
        arr[b] = tmp;
    }

题目:已知一个几乎有序的数组。几乎有序是指,如果把数组排好顺序的话,每个元素移动的距离一定不超过k,并且k相对于数组长度来说是比较小的。

请选择一个合适的排序策略,对这个数组进行排序。

思路:维护k+1长度小根堆,遍历数组前k元素初始化小根堆,数组后续遍历同时poll栈顶元素(就是最终的正确值)

public static void sortedArrDistanceLessK(int[] arr, int k) {
        if (k == 0)
            return;

        PriorityQueue<Integer> queue = new PriorityQueue<>();
        int i = 0;
        while (i <= Math.min(arr.length-1, k - 1)) {
            queue.add(arr[i]);
            i++;
        }
        int index = 0;
        int[] help = new int[arr.length];
        while (i<arr.length){
            queue.add(arr[i]);
            // 第一个位置的最小值一定在queue里面
            help[index++] = queue.poll();
            i++;
        }
        while (!queue.isEmpty()){
            help[index++] = queue.poll();
        }
        i = 0;
        while (i<arr.length){
            arr[i] = help[i];
            i++;
        }
    }
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值