排序-堆排序

给你一个整数数组 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;
    }
}
相关推荐
识醉沉香12 小时前
广度优先遍历
算法·宽度优先
中國龍在廣州12 小时前
现在人工智能的研究路径可能走反了
人工智能·算法·搜索引擎·chatgpt·机器人
快手技术12 小时前
NeurIPS 2025 | 可灵团队提出 Flow-GRPO, 首次将在线强化学习引入流匹配生成模型
算法
星释13 小时前
Rust 练习册 67:自定义集合与数据结构实现
数据结构·算法·rust
前端小L14 小时前
图论专题(十九):DAG上的“关键路径”——极限规划「并行课程 III」
算法·矩阵·深度优先·图论·宽度优先
scx2013100414 小时前
20251116 树状DP总结
算法·深度优先·图论
Aspect of twilight14 小时前
LeetCode华为大模型岗刷题
python·leetcode·华为·力扣·算法题
2301_8079973814 小时前
代码随想录-day47
数据结构·c++·算法·leetcode
Elias不吃糖14 小时前
LeetCode每日一练(3)
c++·算法·leetcode
别动哪条鱼15 小时前
FFmpeg 核心数据结构关系图
数据结构·ffmpeg