Cod sursa(job #782643)

Utilizator balakraz94abcd efgh balakraz94 Data 28 august 2012 15:09:54
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include<cstdio>
#include<stdlib.h>
#include<time.h>
#include<algorithm>
#define infile "algsort.in"
#define outfile "algsort.out"
#define n_max 500005
using namespace std;

int A[n_max];
int N;

void read()
{
	freopen(infile,"r",stdin);
	
	scanf("%d",&N);
	
	for(int i=1;i<=N;i++)
		scanf("%d",&A[i]);
	
	fclose(stdin);
}

void Quick3Way(int lo, int hi){
	if (hi <= lo) 
		return;

	int lt = lo, gt = hi;
	int idx = lo;
	int v = A[lo];
	
	while(idx <= gt){
		if(A[idx] < v)
			swap(A[lt++], A[idx++]);
		else if(A[idx] > v)
			swap(A[idx], A[gt--]);
		else
			idx++;	
	}
	
	Quick3Way(lo, lt-1);
	Quick3Way(gt+1, hi);
}


void RandomShuffle(){
	srand ( time(NULL) );
	
	for(int i=1; i<=N; ++i)
		swap(A[i], A[rand() % N + 1]);
}


void QuickSort()
{
	RandomShuffle();
	
	Quick3Way(1, N);
}


void print()
{
	freopen(outfile,"w",stdout);
	
	for(int i=1;i<=N;i++)
		printf("%d ",A[i]);
	
	fclose(stdout);
}


int main()
{
	read();
	
	QuickSort();
	
	print();
	
	return 0;
}