Cod sursa(job #2219773)

Utilizator Andrei-27Arhire Andrei Andrei-27 Data 9 iulie 2018 17:35:24
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <algorithm>
#include <vector>
#include <cstdio>

using namespace std;



void swap(int a[],int i,int j)
{
 int aux = a[i];
 a[i] = a[j];
 a[j] = aux;

}
void downheap(int a[],int v,int n)
{
 int w = 2 * v + 1; // primul descendent al lui v
 while (w<n)
 {
 if (w+1<n) // mai exista unul?
 if (a[w+1]>a[w]) w++; //crescator
 // w este decendentul lui v
 if (a[v]>=a[w]) return; //crescator
 swap(a,v, w); // interschimbam v cu w
 v = w; // continuam
 w = 2 * v + 1;
 }
}
void heapsort(int a[],int n)
{
 for (int v = n/2-1; v >= 0; v--) //creem heap`ul
 downheap (a,v,n);
 while (n>1)
 {
 n--;
 swap(a,0, n);
 downheap (a,0,n);
 }
}

int main()
{
 int i, x, n,v[100];

 freopen("heapsort.in","r",stdin);
 freopen("heapsort.out","w",stdout);

 scanf("%d",&n);

 for(i = 0; i < n; i++ )
 {
 scanf("%d",&x);
 v[i]=x;
 }

 heapsort(v,n);


 for(i = 0; i < n; i++)
 {
 printf("%d ",v[i]);
 }
 return 0;
}