*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 有序的剩余元素、自上而下

相关推荐
AllData公司负责人9 分钟前
亲测丝滑,体验跃迁|AllData通过集成开源项目RustFS,多模态数据存储新范式
java·大数据·数据库·算法·数据分析·rustfs
磊 子13 分钟前
AVL树的讲解
数据结构·算法
Trouvaille ~20 分钟前
【Redis篇】Hash 哈希:字段级操作与对象存储的最佳实践
数据库·redis·后端·算法·缓存·哈希算法·键值对
悠仁さん27 分钟前
数据结构 树 二叉树 堆 (链式二叉树模拟实现篇)
数据结构·算法
z2005093038 分钟前
今日算法(带回文问题的回溯)
算法·leetcode·回溯
洛水水40 分钟前
【力扣100题】55.编辑距离
算法·leetcode·动态规划
洛水水1 小时前
【力扣100题】62.滑动窗口最大值
数据结构·算法·leetcode
IronMurphy1 小时前
算法五十一 64. 最小路径和
算法
醒醒该学习了!1 小时前
Prompt提示词——带有深度思考模型的提示方法(理论篇)
人工智能·算法·prompt
君为先-bey1 小时前
Latte——视频生成的潜在扩散变换器
算法·机器学习·音视频·扩散模型