Cod sursa(job #796354)

Utilizator claudiumihailClaudiu Mihail claudiumihail Data 11 octombrie 2012 10:12:23
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.54 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <cstdlib>

using std::cout;
using std::endl;
using std::fstream;
using std::vector;

typedef unsigned long ulong;

#define MAXN 500001

ulong vec[MAXN];

int ChoosePivot(int start, int end)
{
    return start + (end-start)/2;
}

void SwapAroundPivot(ulong vec[], int &start, int &end, int pivot)
{
    const ulong pivotValue = vec[pivot];
    while (start <= end)
    {
        while (vec[start] < pivotValue)
        {
            start++;
        }

        while (pivotValue < vec[end])
        {
            end--;
        }
        
        if (start <= end)
        {
            std::swap(vec[start], vec[end]);
            start++;
            end--;
        }
    }
}

void QuickSort(ulong vec[], int start, int end)
{
    if (start < end)
    {
        int newstart = start;
        int newend = end;
        int pivot = ChoosePivot(start, end);
        
        SwapAroundPivot(vec, newstart, newend, pivot);
        
        QuickSort(vec, start, newend);
        QuickSort(vec, newstart, end);
    }
}

int main()
{
    int n;
    fstream fin("algsort.in", fstream::in);
    fstream fout("algsort.out", fstream::out);
    
    fin >> n;
    //cout << n << endl;
    
    for (int i=0; i<n; ++i)
    {
        fin >> vec[i];
    }
    fin.close();

    QuickSort(vec, 0, n-1);
    
    for (int i=0; i<n; ++i)
    {
        fout << vec[i] << ' ';
    }
    //fout << "\n";

    fout.close();
    return 0;
}