排序-堆排序

给你一个整数数组 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;
    }
}
相关推荐
Brookty1 分钟前
【数据结构】Map与Set结构详解
数据结构
WaitWaitWait013 小时前
LeetCode每日一题4.20
算法·leetcode
蒟蒻小袁3 小时前
力扣面试150题--有效的括号和简化路径
算法·leetcode·面试
跳跳糖炒酸奶4 小时前
第十五讲、Isaaclab中在机器人上添加传感器
人工智能·python·算法·ubuntu·机器人
明月看潮生6 小时前
青少年编程与数学 02-018 C++数据结构与算法 06课题、树
数据结构·c++·算法·青少年编程·编程与数学
小指纹6 小时前
动态规划(一)【背包】
c++·算法·动态规划
_安晓6 小时前
数据结构 -- 图的应用(一)
数据结构·算法·图论
阳洞洞6 小时前
leetcode 二分查找应用
算法·leetcode·二分查找
猎猎长风7 小时前
【数据结构和算法】1. 数据结构和算法简介、二分搜索
数据结构·算法
Pasregret7 小时前
模板方法模式:定义算法骨架的设计模式
算法·设计模式·模板方法模式