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

相关推荐
胡小禾40 分钟前
JDK17和JDK8的 G1
jvm·算法
胖咕噜的稞达鸭3 小时前
算法入门:专题攻克一---双指针(3)有效三角形的个数 查找总价格为目标值的两个商品(剑指offer题目)
算法
逻辑留白陈7 小时前
Adaboost进阶:与主流集成算法对比+工业级案例+未来方向
算法
Learn Beyond Limits7 小时前
Mean Normalization|均值归一化
人工智能·神经网络·算法·机器学习·均值算法·ai·吴恩达
天选之女wow8 小时前
【代码随想录算法训练营——Day28】贪心算法——134.加油站、135.分发糖果、860.柠檬水找零、406.根据身高重建队列
算法·leetcode·贪心算法
Gohldg8 小时前
C++算法·贪心例题讲解
c++·数学·算法·贪心算法
远远远远子8 小时前
类与对象 --1
开发语言·c++·算法
Aaplloo8 小时前
【无标题】
人工智能·算法·机器学习
西望云天8 小时前
The 2024 ICPC Asia Nanjing Regional Contest(2024南京区域赛EJKBG)
数据结构·算法·icpc
10岁的博客8 小时前
容器化安装新玩法
算法