栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

堆排序c++代码

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

堆排序c++代码

堆排序

从第一个非叶子节点开始建立大顶堆,然后与堆顶进行交换,重新进行再调整

class Solution
{
public:
    //第二个参数表示剩余未排序数字的数量即堆的大小
    void makeHeap(vector &arr,int heapSize ,int index)
    {
        int left = 2 * index + 1;//左节点
        int right = 2 * index + 2;//右节点
        int maxIndex = index;
        if (left arr[maxIndex])
        {
            maxIndex = left;
        }

        if (right arr[maxIndex])
        {
            maxIndex = right;
        }
        if(maxIndex!=index)
        {
            swap(arr[index], arr[maxIndex]);
            makeHeap(arr, heapSize,maxIndex);
        }
    }
    void heapSort(vector &arr)
    {
        int n = arr.size();
        //初始化堆 从最后一个非叶子节点开始建堆,最后一个非叶子节点就是n/2-1
        for (int i = n / 2 - 1; i >= 0;i--)
        {
            makeHeap(arr, n,i);
        }
        for (int i = n - 1; i > 0;i--)
        {
            //将最大值交换到数组最后
            swap(arr[i], arr[0]);
            //调整剩余数组,使其满足大顶堆
            makeHeap(arr, i,0);
        }
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/512667.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号