ALL > Computer and Education > courses > university courses > undergraduate courses > An Overview of Computer Science > zstu-(2019-2020-1) class > 2019339900028__孟真 >
homework 4-2 sort Version 0
👤 Author: by 1764293088qqcom 2019-10-17 09:46:45
//大根堆
#include<bits/stdc++.h>
using namespace std;
int n,len=0,heap[10086];
void fup(int u)
{
while(1)
{
if(u==1)break;
int fa=u/2;
if(heap[fa] < heap[u])
{
swap(heap[fa],heap[u]);
u=fa;
}
else break;
}
}
void fdown(int u)
{
while(1)
{
int lc=u*2;
int rc=lc+1;
int ll;
if(lc>len)break;
if(lc==len)ll=lc;
else
{
if(heap[lc]>heap[rc])ll=lc;
else ll=rc;
}
if(heap[u]<heap[ll])
{
swap(heap[u],heap[ll]);
u=ll;
}
else break;
}
}
int main()
{
int x;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>x;
len++;
heap[len]=x;
fup(len);
}
for(int i=1;i<n;i++)
{
cout<<heap[1]<<" ";
heap[1]=heap[len];
len--;
fdown(1);
}
cout<<heap[1];
return 0;
}

Please login to reply. Login

Reversion History

Loading...
No reversions found.