HDU 1040 As Easy As A+B(堆排序)

ZMST發表於2018-11-28

題目連結:

是升序

所以先建大堆

可以向下調整

然後再進行逐個換位排序

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<vector>
using namespace std;
#define maxn 10010
int heap[maxn],n;
void downAdjust(int low,int high)
{
    int i=low;
    int j=i*2;
    while (j<=high)
    {
        if(j+1<=high&&heap[j+1]>heap[j])
        {
            j=j+1;
        }
        if(heap[j]>heap[i])
        {
            swap(heap[j], heap[i]);
            i=j;
            j=i*2;
        }
        else
        {
            break;
        }
    }
}
void createHeap()
{
    for(int i=n/2;i>=1;i--)
    {
        downAdjust(i, n);
    }
}
void heapSort()
{
    createHeap();
    for(int i=n;i>1;i--)
    {
        swap(heap[i], heap[1]);
        downAdjust(1, i-1);
    }
    for(int i=1;i<=n-1;i++)
    {
        printf("%d ",heap[i]);
    }
    printf("%d\n",heap[n]);
}
int main()
{
    int t;
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
        {
            scanf("%d",&heap[i]);
        }
        heapSort();
    }
    return 0;
}

 

相關文章