Cod sursa(job #883128)

Utilizator BitOneSAlexandru BitOne Data 19 februarie 2013 19:06:21
Problema Sortare prin comparare Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <algorithm>

using namespace std;

vector<int> v;

inline void _swap(int& x, int& y) {int aux = x; x = y; y = aux;}
int partition(int left, int right, int pIndex)
{
    int pValue, i, j;

    pValue = v[pIndex];
    _swap(v[left], v[pIndex]);

    for(i = j = left + 1; j <= right; ++j)
    {
	if(v[j] < pValue)
	{
	    swap(v[j], v[i]);
	    ++i;
	}
    }
    _swap(v[left], v[i-1]);

    return i - 1;    
}

inline void QuickSort(int left, int right)
{
    if(left >= right) return;
    if(1 == right - left)
    {
	if(v[left] > v[right])
	{
	    _swap(v[left], v[right]);
	}
        return;
    } 

    int pIndex = partition(left, right, left);

    QuickSort(left, pIndex - 1);
    QuickSort(pIndex + 1, right);
}

int main()
{
    int N;
    ifstream in("algsort.in");
    ofstream out("algsort.out");

    in >> N;
    copy(istream_iterator<int>(in), istream_iterator<int>(), back_inserter(v));

    QuickSort(0, N - 1);

    copy(v.begin(), v.end(), ostream_iterator<int>(out, " "));
    out << '\n';

    return EXIT_SUCCESS;
}