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

相关推荐
SoleMotive.28 分钟前
redis实现漏桶算法--https://blog.csdn.net/m0_74908430/article/details/155076710
redis·算法·junit
-森屿安年-35 分钟前
LeetCode 283. 移动零
开发语言·c++·算法·leetcode
北京地铁1号线43 分钟前
数据结构:堆
java·数据结构·算法
散峰而望1 小时前
C++数组(一)(算法竞赛)
c语言·开发语言·c++·算法·github
自然常数e1 小时前
深入理解指针(1)
c语言·算法·visual studio
WWZZ20251 小时前
快速上手大模型:深度学习13(文本预处理、语言模型、RNN、GRU、LSTM、seq2seq)
人工智能·深度学习·算法·语言模型·自然语言处理·大模型·具身智能
Christo32 小时前
AAAI-2024《Multi-Class Support Vector Machine with Maximizing Minimum Margin》
人工智能·算法·机器学习·支持向量机·数据挖掘
元亓亓亓3 小时前
LeetCode热题100--79. 单词搜索
算法·leetcode·职场和发展
司铭鸿3 小时前
化学式解析的算法之美:从原子计数到栈的巧妙运用
linux·运维·服务器·算法·动态规划·代理模式·哈希算法
ekprada4 小时前
DAY 18 推断聚类后簇的类型
算法·机器学习·支持向量机