排序-堆排序

给你一个整数数组 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;
    }
}
相关推荐
sali-tec35 分钟前
C# 基于halcon的视觉工作流-章56-彩图转云图
人工智能·算法·计算机视觉·c#
黑岚樱梦4 小时前
代码随想录打卡day23:435.无重叠区间
算法
Kuo-Teng5 小时前
Leetcode438. 找到字符串中所有字母异位词
java·算法·leetcode
gihigo19985 小时前
MATLAB使用遗传算法解决车间资源分配动态调度问题
算法·matlab
墨染点香5 小时前
LeetCode 刷题【138. 随机链表的复制】
算法·leetcode·链表
却道天凉_好个秋6 小时前
目标检测算法与原理(一):迁移学习
算法·目标检测·迁移学习
兮山与7 小时前
算法24.0
算法
晓北斗NorSnow7 小时前
机器学习核心算法与学习资源解析
学习·算法·机器学习
hans汉斯8 小时前
【计算机科学与应用】基于BERT与DeepSeek大模型的智能舆论监控系统设计
大数据·人工智能·深度学习·算法·自然语言处理·bert·去噪