八大排序之堆排序C++详解/C++堆排序/堆排

八大排序之堆排序C++详解/C++堆排序/堆排

题目链接

在这里插入图片描述
912. 排序数组

思路分析

在这里插入图片描述

代码实现

class Solution {
public:
    void Swap(int& a, int& b)
    {
        int tmp = a;
        a = b;
        b = tmp;
    }
    void adjustDown(vector<int>& nums, int root, int n)
    {
        int parent = root;
        int child = parent*2 + 1;
        //这里建立的是一个大顶堆,因此要找子结点中较大的一个
        while(child < n)
        {
            if( (child+1) < n &&  nums[child] < nums[child+1])
                child++;
            if(nums[parent] < nums[child])
            {
                Swap(nums[parent], nums[child]);
                parent = child;
                child = parent*2 + 1;
            }
            else
                break;
        }

    }
    vector<int> sortArray(vector<int>& nums) {
        //先建堆 从最后一个节点的父节点开始
        int n = nums.size();
        for(int i = ((n-1)-1)/2; i >= 0; --i)
        {
            adjustDown(nums, i, n);
        }

        int end = n-1;
        while(end > 0)
        {
            Swap(nums[0], nums[end]);
            adjustDown(nums, 0, end);
            --end;
        }
        return nums;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值