Cod sursa(job #800591)

Utilizator igsifvevc avb igsi Data 22 octombrie 2012 05:13:03
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
/*
 * Randomized Quicksort which switches to selection sort
 * when the size of the subarray is small enough.
 * Also in the partitioning step we use two pivots and partition
 * the array into three: smaller, equal and larger.
 */
#include <fstream>
#include <cstdlib>
using namespace std;

ifstream fin("algsort.in");
ofstream fout("algsort.out");

int sw = 15;
int v[500001], n;

void quicksort(int l, int r)
{
	if(r - l > sw)
	{
		/* finding the pivot element and partitionig around it */
		int i, q, j, aux;
        
		i = l + rand() % (r-l+1); // pick a random pivot
		aux = v[i]; v[i] = v[r]; v[r] = aux;

		for(i = l-1, q = l-1, j = l; j <= r-1; j++)
			if(v[j] <= v[r])
			{
				aux = v[++i];
				v[i] = v[j];
				v[j] = aux;
				if(v[i] < v[r])
				{
				   q++;
				   if(q != i) 
				   {
					   aux = v[q];
					   v[q] = v[i];
					   v[i] = aux;
				   }
				}
			}
		aux = v[++i];
		v[i] = v[r];
		v[r] = aux;
		/* finished partitioning */

		quicksort(l, q);
		quicksort(i+1, r);
    	
	}        
	else if(l < r)
	{
		int i, j, aux;
		for(i = l+1; i <= r; ++i)
			for(j = i-1; j >= l && v[j] > v[j+1]; --j)
			{
				aux = v[j]; v[j] = v[j+1]; v[j+1] = aux;
			}
	}          
}

int main()
{
    int i;
	srand(16);

	fin >> n;
	for(i = 1; i <= n; ++i)
		fin >> v[i];

	quicksort(1, n);

	for(i = 1; i <= n; ++i)
		fout << v[i] << ' ';
	fout << endl;

	fin.close();
	fout.close();
	return 0;
}