Cod sursa(job #1196680)

Utilizator stef93Stefan Gilca stef93 Data 8 iunie 2014 18:34:33
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <fstream>
#include <cstdlib>
#include <ctime>

using namespace std;

void swap(int &a, int &b) {
	int temp;

	temp = a;
	a = b;
	b = temp;
}

int part(int a[], int low, int high) {
	int i = low, j = high;
	int pivot = a[(low + high) / 2];

	while (i <= j) {
		while (a[i] < pivot && i < high) {
			i++;
		}
		while (a[j] > pivot && j > low) {
			j--;
		}

		if (i <= j) {
			swap(a[i], a[j]);
			i++;
			j--;
		}
	}
	return i;
}

void quick_sort(int a[], int low, int high) {
	int k;

	while (low < high) {
		k = part(a, low, high);

		if (k - low > high - k) {
			quick_sort(a, low, k - 1);
			low = k;
		} else {
			quick_sort(a, k, high);
			high = k;
		}
	}
}

int main() {
	int a[500003];
	int n, i;
	ifstream in("algsort.in");
	ofstream out("algsort.out");
	in >> n;
	for (i = 0; i < n; i++) {
		in >> a[i];
	}
	in.close();
	quick_sort(a, 0, n - 1);

	for (i = 0; i < n; i++) {
		out << a[i] << ' ';
	}
	out << '\n';
	out.close();
	return 0;
}