Cod sursa(job #1460551)

Utilizator glbglGeorgiana bgl glbgl Data 13 iulie 2015 06:50:19
Problema Sortare prin comparare Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

int N;
vector<int> v;

void read(){

	in >> N;
	v.resize(N+1);
	int x;
	for(int i = 1; i <= N; ++i){
		in >> x;
		v[i] = x;
	}
}

// void swap(int *x, int *y){

//  	int tmp = *x;
//  	*x = *y;
//  	*y = tmp;
// }

int partition(int l, int r){
	int pivot_index = (l+r)/2;
	int pivot = v[pivot_index];
	swap(v[pivot_index], v[r]);
	int store_index = l;
	for(int i = l; i <= r-1; ++i){
		if(v[i] < pivot){
			swap(v[i], v[store_index]);
			store_index++;
		}
	}
	swap(v[store_index], v[r]);
	return store_index;
}


void Quicksort(int l, int r){

	if(l < r){
		int p = partition(l, r);
		Quicksort(l, p);
		Quicksort(p+1, r);
	}
}


void write(){

	for(int i = 1; i <= N; ++i){
		out << v[i] << " ";
	}
}


int main(){

	ios::sync_with_stdio(false);
	read();
	Quicksort(1, N);
	write();
}