Cod sursa(job #439239)

Utilizator alexandru92alexandru alexandru92 Data 11 aprilie 2010 14:34:34
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
/* 
 * File:   main.cpp
 * Author: VirtualDemon
 *
 * Created on April 11, 2010, 2:08 PM
 */
#include <vector>
#include <cstdlib>
#include <fstream>
#include <iterator>

/*
 * 
 */
using namespace std;
vector< int > v;
inline void DownHeap( int from, int to )
{
    for( int son=2*from; son <= to; from=son, son=2*from )
    {
        if( son < to && v[son+1] > v[son] )
            ++son;
        if( v[from] >= v[son] )
            return;
        swap( v[from], v[son] );
    }
}
inline void HeapSort( int from, int to )
{
    int i;
    for( i=(to-from+1)/2; i >= 0; --i )
        DownHeap( i, to );
    while( to >= from )
    {
        swap( v[from], v[to] );
        --to;
        DownHeap( from, to );
    }
}
inline void IntroSort( int left, int right, int depthLimit )
{
    if( left < right )
    {
        if( !depthLimit )
        {
            HeapSort( left, right );
            return;
        }
        int leftPtr=left, rightPtr=right, pValue=v[ left+(right-left)/2 ];
        for( ; ; )
        {
            for( ; pValue > v[leftPtr]; ++leftPtr );
            for( ; pValue < v[rightPtr]; --rightPtr );
            if( leftPtr > rightPtr )
                break;
            swap( v[leftPtr], v[rightPtr] );
            ++leftPtr, --rightPtr;
        }
        if( left < rightPtr )
            IntroSort( left, rightPtr, depthLimit-1 );
        if( leftPtr < right )
            IntroSort( leftPtr, right, depthLimit-1 );
    }
}
inline int Log2( int N )
{
    int i;
    for( i=1;  i < N; i<<=1 );
    return i;
}
int main(int argc, char** argv)
{
    int N;
    ifstream in( "algsort.in" );
    in>>N;
    copy( istream_iterator<int>(in), istream_iterator<int>(), back_inserter(v) );
    IntroSort( 0, N-1, Log2(N) );
    ofstream out( "algsort.out" );
    copy( v.begin(), v.end(), ostream_iterator<int>( out, " " ) );
    out<<'\n';
    return EXIT_SUCCESS;
}