堆排序

测试链接:https://www.luogu.com.cn/problem/P1177
视频参照左神的视频总结的,视频链接:
【算法讲解025【必备】堆结构和堆排序】 https://www.bilibili.com/video/BV1fu4y1q77y/?share_source=copy_web&vd_source=b743161248f2812166d8471922edab74

介绍

一种是自上而下建堆,一种是自下而上建堆(时间复杂度O(nlogn)),相比之下,自下而上建堆的时间复杂度更低(时间复杂度O(n)),所以第二种的堆排序更优,但由于后面堆排序的的弹出流程不变,时间复杂度为O(nlogn),所以总体上的时间复杂度为O(nlogn)

代码


#include <bits/stdc++.h>
using namespace std;
const int N=1e5+10;
typedef long long ll;
int n;
int arr[N];

void heapinsert(int i)
{
    while(arr[i]>arr[(i-1)/2])
    {
        swap(arr[i],arr[(i-1)/2]);
        i = (i-1)/2;
    }
}

void heapify(int i,int size)
{
    int l = i*2 + 1;
    while(l<size)
    {
        int best = l+1 <size && arr[l+1]>arr[l]? l+1:l;
        best = arr[best]>arr[i] ? best:i;
        swap(arr[best],arr[i]);
        if(best == i) break;
        i = best;
        l = i*2 + 1; 
    }


}


void heapsort()
{
    for(int i=0;i<n;i++)
    {
        heapinsert(i);
    }

    int size = n;
    while(size>1)
    {
        swap(arr[0],arr[--size]);
        heapify(0,size);

    }
}



void heapsort2()
{
    for(int i=n-1;i>=0;i--)
    {
        heapify(i,n);
    }

    int size = n;
    while(size>1)
    {
        swap(arr[0],arr[--size]);
        heapify(0,size);

    }
}


int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=0;i<n;i++)cin>>arr[i];
    heapsort2();
    for(int i=0;i<n;i++)cout<<arr[i]<<' ';
    cout<<endl;

    return 0;
}

posted @ 2025-05-29 22:19  屈臣  阅读(22)  评论(0)    收藏  举报