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

相关推荐
Swift社区几秒前
LeetCode 469 凸多边形
算法·leetcode·职场和发展
chilavert3183 分钟前
技术演进中的开发沉思-298 计算机原理:算法的本质
算法·计算机原理
Aaron15889 分钟前
全频段SDR干扰源模块设计
人工智能·嵌入式硬件·算法·fpga开发·硬件架构·信息与通信·基带工程
求梦82014 分钟前
【力扣hot100题】缺失的第一个正数(12)
数据结构·算法·leetcode
散峰而望30 分钟前
【算法竞赛】顺序表和vector
c语言·开发语言·数据结构·c++·人工智能·算法·github
千金裘换酒31 分钟前
LeetCode 回文链表
算法·leetcode·链表
CSDN_RTKLIB31 分钟前
【std::map】与std::unordered_map差异
算法·stl·哈希算法
FL1717131432 分钟前
Geometric Control
人工智能·算法
老鼠只爱大米35 分钟前
LeetCode算法题详解 283:移动零
算法·leetcode·双指针·快慢指针·移动零·move zeroes
过河卒_zh156676639 分钟前
喜讯:第十五批生成合成类算法备案备案号公布
人工智能·算法·aigc·生成式人工智能·算法备案