Cod sursa(job #796334)

Utilizator claudiumihailClaudiu Mihail claudiumihail Data 11 octombrie 2012 09:04:42
Problema Sortare prin comparare Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 1.99 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;

int ChoosePivot(int start, int end)
{
    return start + std::rand()%(end-start);
}

int SwapAroundPivot(vector<ulong>& vec, int start, int end, int pivot)
{
    int newPivotPose = pivot;
    while (start <= newPivotPose || newPivotPose <= end)
    {
        while (start <= newPivotPose && vec[start] <= vec[newPivotPose])
        {
            start++;
        }
        
        if (start <= newPivotPose && vec[start] > vec[newPivotPose])
        {
            std::swap(vec[start], vec[newPivotPose]);
            newPivotPose = start;
        }

        while (newPivotPose <= end && vec[newPivotPose] <= vec[end])
        {
            end--;
        }
        
        if (newPivotPose <= end && vec[newPivotPose] > vec[end])
        {
            std::swap(vec[end], vec[newPivotPose]);
            newPivotPose = end;
        }
    }
    
    return newPivotPose;
}

void QuickSort(vector<ulong>& vec, int start, int end)
{
    if (start < end)
    {
        int pivot = ChoosePivot(start, end);
        
        /*cout << "Start = " << start << endl;
        cout << "End = " << end << endl;
        cout << "Pivot = " << pivot << endl;*/
        
        pivot = SwapAroundPivot(vec, start, end, pivot);
        
        QuickSort(vec, start, pivot);
        QuickSort(vec, pivot+1, end);
    }
}

int main()
{
    int n;
    vector<ulong> v;
    fstream fin("algsort.in", fstream::in);
    fstream fout("algsort.out", fstream::out);
    
    fin >> n;
    //cout << n << endl;
    
    v.resize(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] << " ";
    }
    //fout << "\n";
    
    fin.close();
    fout.close();
    return 0;
}