Cod sursa(job #460465)

Utilizator BitOneSAlexandru BitOne Data 2 iunie 2010 19:25:00
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#define Nmax 500111

/*
 *
 */
using namespace std;
int v[Nmax];
inline int MedianOf3( int x, int y, int z )
{
    if( x >= y )
    {
        if( y >= z ) // the order is x >= y >= z
            return y;
        else if( z >= x ) //the order is z >= x >= y
                return x;
        return z; //the order is x >= z >= y
    }
    else if( y >= z ) // so we know that x <= y and y >=z
         {
             if( x >= z ) //the order is y >= x >= z
                return x;
            else return z;
         }
    //neither x >= y and y >=z is true => x <= y and y <= z
    return y;
}
inline void QSort( int left, int right )
{
    if( left < right )
    {
        int middle=left+(right-left)/2, lleft=left-1, rright=right+1, pValue=MedianOf3( v[left], v[middle], v[right] );
        while( true )
        {
            while( pValue > v[++lleft] );
            while( pValue < v[--rright] );
            if( lleft > rright )
                break;
            swap( v[lleft], v[rright] );
        }
        if( lleft < right )
            QSort( lleft, right );
        if( rright > left )
            QSort( left, rright );
    }
}
int main( void )
{
    int N;
    ifstream in( "algsort.in" );
    in>>N;
    copy( istream_iterator<int>(in), istream_iterator<int>(), v+1 );
    QSort( 1, N );
    ofstream out( "algsort.out" );
    copy( v+1, v+N+1, ostream_iterator<int>(out, " " ) );
    out<<'\n';
    return EXIT_SUCCESS;
}