排序-堆排序

给你一个整数数组 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;
    }
}
相关推荐
Funny_AI_LAB6 分钟前
MetaAI最新开源Llama3.2亮点及使用指南
算法·计算机视觉·语言模型·llama·facebook
NuyoahC13 分钟前
算法笔记(十一)——优先级队列(堆)
c++·笔记·算法·优先级队列
jk_10115 分钟前
MATLAB中decomposition函数用法
开发语言·算法·matlab
penguin_bark1 小时前
69. x 的平方根
算法
一休哥助手1 小时前
Redis 五种数据类型及底层数据结构详解
数据结构·数据库·redis
这可就有点麻烦了1 小时前
强化学习笔记之【TD3算法】
linux·笔记·算法·机器学习
苏宸啊1 小时前
顺序表及其代码实现
数据结构·算法
lin zaixi()1 小时前
贪心思想之——最大子段和问题
数据结构·算法
FindYou.1 小时前
C - Separated Lunch
算法·深度优先
夜雨翦春韭1 小时前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法