*LEEDCODE 912排序数组

cpp 复制代码
class Solution {
public:

    vector<int> sortArray(vector<int>& nums) {
        Heapsort(nums);
        return nums;
    }
    void Heapsort(vector<int>& nums)
    {
        int n = nums.size();
        for(int i = (n/2) - 1; i>=0; i--)
        {
            Adjustdown(nums, i, n);
        }
        for(int i = n-1; i>=0; i--)
        {
            swap(nums[0], nums[i]);
            Adjustdown(nums, 0, i);  
        }


    }
    void Adjustdown(vector<int>& nums, int root, int n)
    {
        int lson = 2 * root + 1;
        while(lson < n)
        {
            if((lson + 1) < n && nums[lson] < nums[lson + 1])
            {
                lson = lson + 1;
            }
            if(nums[lson] > nums[root])
            {
                swap(nums[lson], nums[root]);
                root = lson;
                lson = 2 * root + 1;
            }
            else
                break;
        }
    }
    void swap(int& a, int& b)
    {
        int tmp;
        tmp = a;
        a = b;
        b = tmp;
    }
    
};

堆排序

分两步:

1 大顶堆

2 有序的剩余元素、自上而下

相关推荐
兮山与26 分钟前
算法24.0
算法
晓北斗NorSnow38 分钟前
机器学习核心算法与学习资源解析
学习·算法·机器学习
hans汉斯2 小时前
【计算机科学与应用】基于BERT与DeepSeek大模型的智能舆论监控系统设计
大数据·人工智能·深度学习·算法·自然语言处理·bert·去噪
多喝开水少熬夜2 小时前
损失函数系列:focal-Dice-vgg
图像处理·python·算法·大模型·llm
立志成为大牛的小牛3 小时前
数据结构——三十七、关键路径(王道408)
数据结构·笔记·程序人生·考研·算法
ytttr8733 小时前
基于MATLAB的Relief算法特征权重选择实现
算法
Freshman小白4 小时前
python算法打包为docker镜像(边缘端api服务)
python·算法·docker
mit6.8244 小时前
[VT-Refine] Simulation | Fine-Tuning | docker/run.sh
算法
朴shu4 小时前
Delta数据结构:深入剖析高效数据同步的奥秘
javascript·算法·架构
mit6.8245 小时前
博弈dp|凸包|math分类
算法