Cod sursa(job #824763)

Utilizator costel93FMI - Dumea Eduard Constantin costel93 Data 26 noiembrie 2012 22:03:22
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include<iostream.h>
#include<fstream.h>
#include<vector>

using namespace std;

ifstream f("algsort.in");
ofstream g("algsort.out");

vector <int> heap;
int n, i, x;

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(vector <int> &heap)
{
	return heap[1];
}

int max(vector <int> &heap, int a, int b)
{
	if(heap[a] > heap[b])
		return a;
	return b;
}

void sift(vector <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( vector <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(vector <int> &heap, int n) 
{
    for (int i = n / 2; i > 0; --i) 
	{
        sift(heap, n, i);
    }
}

void cut( vector <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);
	}
	heap.pop_back();
}

void insert(vector <int> &heap, int &n, int val)
{
	++n;
	heap.push_back(val);
	percolate(heap, n, n);
}

void printf(vector <int> &heap, int n)
{
	int i;
	
	for(i=1; i<=n; ++i)
		g<<heap[i]<<" ";
	g<<"\n";
}


void heapsort(vector <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);
	}
	//printf(heap, n);

}

 int main()
 {
	f>>n;
	
	heap.push_back(n);
	
	for( i=1; i <= n; ++i)
	{
		f>>x;
		heap.push_back(x);
	}
	
	heapsort(heap, n);
	
	printf(heap, n);
	
	return 0;
 }