堆排序练习题

#include <vector>
using namespace std;
class HeapSort
{
private:
    int len;
    vector<int> list;
    void SwapNode(int i,int heapSize);
public:
    void Sort();
    void Print();
    HeapSort(void);
    ~HeapSort(void);
};

#include <iostream>
#include "HeapSort.h"
using namespace std;
HeapSort::HeapSort(void)
{
    len = 10;
}
HeapSort::~HeapSort(void){}
void HeapSort::SwapNode(int i,int heapSize)
{
    int l = i*2;
    int r = i*2 +1 ;
     
    int max = i;
    if(l<=heapSize && list[l-1] > list[i-1])
        max = l;
    if(r<=heapSize && list[r-1] > list[l-1])
        max = r;
     
    if(max != i)
    {
        int tmp = list[max-1];
        list[max-1] = list[i-1];
        list[i-1] = tmp;
        SwapNode(max,heapSize);
    }
}
 
void HeapSort::Sort()
{
    for(int i=len/2;i>0;i--)
    {
        SwapNode(i,len);
    }
 
    int heapSize = len;
    for(int i=len-1;i>0;i--)
    {
        int tmp = list[i];
        list[i] = list[0];
        list[0] = tmp;
        SwapNode(1,--heapSize);
    }
}
void HeapSort::Print()
{
    for(int i=0;i<len;i++)
    {
        int rnd = rand()%100;
        list.push_back(rnd);
        cout<<rnd << " ";
    }
    cout<<endl;
    Sort();
    for(int i=0;i<len;i++)
    {
        cout<<list[i]<<" ";
    }
    cout<<endl;
}

堆排序是默认把数组看作一个二叉树,第一步是把数组顺序按从小到大由顶向下调整(最大堆),

第二步,取出堆(树)中的最后一个数,并把这个数放在堆顶,把最大的堆顶的数拿出。改变堆的元素个数(已经拿掉了个数),从新调整堆顶的那个比较小的数。

第二步显然有大量无意义的对比。 大致看来 堆排序性能不高,复杂度最高最低都是nlogn

posted @   君之蘭  阅读(2826)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示