排序-堆排序

给你一个整数数组 nums,请你将该数组升序排列。

复制代码
输入:nums = [5,2,3,1]
输出:[1,2,3,5]

输入:nums = [5,1,1,2,0,0]
输出:[0,0,1,1,2,5]

思路直接看我录制的视频吧 算法-堆排序_哔哩哔哩_bilibili

实现代码如下所示:

java 复制代码
class Solution {
    public int[] sortArray(int[] nums) {
        if (nums == null || nums.length == 1) {
            return nums;
        }
        headSort(nums);
        return nums;
    }

    private void headSort(int[] nums) {
        for (int i = (nums.length - 1) / 2; i >=0; i--) {
            adjustHead(nums, i, nums.length);
        }
        for (int i = nums.length - 1; i >0; i--) {
            int temp = nums[i];
            nums[i] = nums[0];
            nums[0] = temp;
            adjustHead(nums, 0, i);
        }
    }

    private void adjustHead(int[] nums, int parent, int length) {
        int temp = nums[parent];
        int maxChildIndex = parent * 2 + 1;
        while (maxChildIndex < length) {
            int rightChild = maxChildIndex + 1;
            if (rightChild < length && nums[rightChild] > nums[maxChildIndex]) {
                maxChildIndex++;
            }
            if (maxChildIndex < length && nums[maxChildIndex] < temp) {
                break;
            }
            nums[parent] = nums[maxChildIndex];
            parent = maxChildIndex;
            maxChildIndex = maxChildIndex * 2 + 1;
        }
        nums[parent] = temp;
    }
}
相关推荐
qiqsevenqiqiqiqi7 分钟前
一维dp知识点
算法·动态规划
ZHANG13HAO11 分钟前
蚁群算法(蚁聚算法)深度解析与 mTSP 实战:物流多车协同配送优化
人工智能·算法·机器学习
D_C_tyu14 分钟前
HTML | 基于权重评估算法实现自动游戏功能的俄罗斯方块小游戏
算法·游戏·html
BUTCHER515 分钟前
G1数据结构
数据结构
小肝一下20 分钟前
每日两道力扣,day1
算法·leetcode·职场和发展
WBluuue21 分钟前
AtCoder Beginner Contest 451(ABCDEFG)
c++·算法
im_AMBER23 分钟前
Leetcode 151 最大正方形 | 买卖股票的最佳时机 III
数据结构·算法·leetcode·动态规划
Fly Wine24 分钟前
Leetcode之简单题:在区间范围内统计奇数数目
算法·leetcode·职场和发展
CoderCodingNo26 分钟前
【GESP】C++五级练习题 luogu-P1102 A-B 数对
开发语言·c++·算法
切糕师学AI28 分钟前
深入理解倒排索引(Inverted Index):搜索引擎的核心数据结构
数据结构·搜索引擎·inverted-index