Cod sursa(job #1814890)

Utilizator horatiucheval2Horatiu Andrei Cheval horatiucheval2 Data 24 noiembrie 2016 17:33:08
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>

using namespace std;

const int MAX = 500000;



void quicksort(int v[], int st, int dr){
    int p1 = v[rand() % (dr - st+1) + st];
    int p2 = v[rand() % (dr - st+1) + st];
    int p3 = v[rand() % (dr - st+1)+st];
    int piv = min(max(p1, p2), p3);
    int i = st, j = dr;
    while(i <= j){
		while(v[i] < piv){
			i++;
		}
		while(v[j] > piv){
			j--;
		}
		if(i <= j){
			swap(v[i], v[j]);

		i++;
		j--;
		}
    }
    if(i < dr){
		quicksort(v, i, dr);
    }
    if(st < j){
		quicksort(v, st, j);
    }
}

int main(){
	ifstream fin("algsort.in");
	ofstream fout("algsort.out");
	srand(time(NULL));

	int n, v[MAX];
	fin >> n;
	for(int i = 0; i < n; i++){
		fin >> v[i];
	}

	quicksort(v, 0, n - 1);
	for(int i = 0; i < n; i++){
		fout << v[i] << " ";
	}

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