Pagini recente » Cod sursa (job #952687) | Cod sursa (job #2238805) | Cod sursa (job #2706744) | Cod sursa (job #1126890) | Cod sursa (job #824549)
Cod sursa(job #824549)
#include<fstream>
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int heap[1000000], n, i;
int father(int x)
{
return x/2;
}
int left_son(int x)
{
return x*2;
}
int right_son(int x)
{
return x*2+1;
}
int maxim(int heap[])
{
return heap[1];
}
int max(int heap[], int a, int b)
{
if(heap[a] > heap[b])
return a;
return b;
}
void sift(int heap[], int n, int x)
{
int aux1, aux2;
while( ( left_son(x) <= n && heap[x] < heap[left_son(x)] ) || ( right_son(x)<=n && heap[x] < heap[right_son(x)] ) )
{
if(right_son(x)<=n)
aux1=max( heap, left_son(x), right_son(x) );
else
aux1=left_son(x);
aux2=heap[aux1];
heap[aux1]=heap[x];
heap[x]=aux2;
x=aux1;
}
}
void percolate( int heap[], int n, int x )
{
int aux = heap[x];
while( (x > 1) && (aux > heap[father(x)]) )
{
heap[x] = heap[father(x)];
x = father(x);
}
heap[x]=aux;
}
void build_heap(int heap[], int n)
{
for (int i = n / 2; i > 0; --i)
{
sift(heap, n, i);
}
}
void cut( int heap[], int &n, int x)
{
if( heap[x] > heap[n])
{
heap[x]=heap[n];
n--;
percolate(heap, n, x);
}
else
{
heap[x]=heap[n];
n--;
sift(heap, n, x);
}
}
void insert(int heap[], int &n, int val)
{
heap[++n]=val;
percolate(heap, n, n);
}
void heapsort(int heap[], int n)
{
int aux;
build_heap(heap, n);
for(i=n; i>=2; --i)
{
aux=heap[1];
heap[1]=heap[i];
heap[i]=aux;
sift(heap, i-1, 1);
}
}
void printf(int heap[], int n)
{
int i;
for(i=1; i<=n; ++i)
g<<heap[i]<<" ";
}
int main()
{
f>>n;
for( i=1; i <= n; ++i)
f>>heap[i];
heapsort(heap, n);
printf(heap, n);
return 0;
}