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

相关推荐
zy_destiny27 分钟前
【非机动车检测】用YOLOv8实现非机动车及驾驶人佩戴安全帽检测
人工智能·python·算法·yolo·机器学习·安全帽·非机动车
rigidwill6661 小时前
LeetCode hot 100—搜索二维矩阵
数据结构·c++·算法·leetcode·矩阵
短尾黑猫1 小时前
[LeetCode 1696] 跳跃游戏 6(Ⅵ)
算法·leetcode
矛取矛求1 小时前
栈与队列习题分享(精写)
c++·算法
袖清暮雨1 小时前
【专题】搜索题型(BFS+DFS)
算法·深度优先·宽度优先
LuckyLay2 小时前
LeetCode算法题(Go语言实现)_46
算法·leetcode·golang
alicema11112 小时前
Python-Django集成yolov识别模型摄像头人数监控网页前后端分离
开发语言·后端·python·算法·机器人·django
胡乱儿起个名2 小时前
C++ 标准库中的 <algorithm> 头文件算法总结
开发语言·c++·算法
uhakadotcom3 小时前
使用NLTK和jieba进行中文情感分析的简单教程
算法·面试·github