排序-堆排序

给你一个整数数组 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;
    }
}
相关推荐
小赵起名困难户1 小时前
蓝桥杯备赛1-2合法日期
算法
shichaog1 小时前
腿足机器人之八- 腿足机器人动力学
算法·机器人
悄悄敲敲敲3 小时前
C++:dfs习题四则
c++·算法·深度优先
牛大了20235 小时前
[LeetCode力扣hot100]-二叉树相关手撕题
算法·leetcode·职场和发展
ll7788115 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
德先生&赛先生5 小时前
LeetCode-633. 平方数之和
数据结构·算法·leetcode
coding_rui7 小时前
链表(C语言版)
c语言·数据结构·链表
coding_rui7 小时前
哈希表(C语言版)
c语言·数据结构·散列表
coding_rui7 小时前
二叉树(C语言版)
c语言·数据结构
mengyoufengyu7 小时前
算法12-贪心算法
python·算法·贪心算法