HeapSort -- 堆排序

本文介绍了一种基于最大堆的数据结构实现,并详细解释了如何通过该数据结构进行堆排序的过程。文中提供了一个具体的C++代码示例,包括构建最大堆、获取子节点索引、维护最大堆性质的方法及堆排序算法。
struct HEAP
{
    vector<int> arr;
    int sizeHeap;

    explicit HEAP(const vector<int> &src)
    {
        sizeHeap = src.size();
        arr = src;
        buildMaxHeap();
    }

    // Get the left child index
    inline int Left(int i)
    {
        return (i << 1) + 1;
    }

    // Get the right child index
    inline int Right(int i)
    {
        return (i << 1) + 2;
    }

    // Max heap
    void maxHeapify(int index)
    {
        int l = Left(index);
        int r = Right(index);
        int largest = -1;

        if(l < sizeHeap and arr[l] > arr[index])
            largest = l;
        else
            largest = index;

        if(r < sizeHeap and arr[r] > arr[largest])
            largest = r;

        if(largest not_eq index)
        {
            std::swap(arr[index], arr[largest]);
            maxHeapify(largest);
        }
    }

    // Build a max heap
    void buildMaxHeap()
    {
        for(int i = (arr.size() - 1) / 2; i >= 0; --i)
        {
            maxHeapify(i);
        }
    }

    // Heap sort
    vector<int> heapSort()
    {
        for(int i = arr.size() - 1; i >= 1; --i)
        {
            std::swap(arr[0], arr[i]);
            --sizeHeap;
            maxHeapify(0);
        }

        return arr;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值