排序-堆排序

给你一个整数数组 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;
    }
}
相关推荐
thusloop1 小时前
380. O(1) 时间插入、删除和获取随机元素
数据结构·算法·leetcode
MobotStone1 小时前
无代码+AI时代,为什么你仍然需要像个开发者一样思考
人工智能·算法
緈福的街口2 小时前
【leetcode】584. 寻找用户推荐人
算法·leetcode·职场和发展
future14122 小时前
游戏开发日记
数据结构·学习·c#
今天背单词了吗9802 小时前
算法学习笔记:17.蒙特卡洛算法 ——从原理到实战,涵盖 LeetCode 与考研 408 例题
java·笔记·考研·算法·蒙特卡洛算法
Maybyy2 小时前
力扣242.有效的字母异位词
java·javascript·leetcode
wjcurry2 小时前
完全和零一背包
数据结构·算法·leetcode
hie988942 小时前
采用最小二乘支持向量机(LSSVM)模型预测气象
算法·机器学习·支持向量机
qq_433554543 小时前
C++ 选择排序、冒泡排序、插入排序
数据结构
python_tty3 小时前
排序算法(一):冒泡排序
数据结构·算法·排序算法