Cod sursa(job #354121)

Utilizator alexandru92alexandru alexandru92 Data 7 octombrie 2009 09:47:17
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.74 kb
#include <fstream>
#include <cstdlib>
/*
#include <fstream.h>
#include <stdlib.h>
*/
#define InFile "algsort.in"
#define OutFile "algsort.out"

using namespace std;
ifstream in;
ofstream out;

class IntroSort
{
  unsigned *v;
  unsigned size;
  inline void swap( unsigned, unsigned );
  inline unsigned medianof3( unsigned, unsigned, unsigned );
  void downheap( unsigned, unsigned );
  void HeapSort( unsigned, unsigned );
  inline void QSort( unsigned, unsigned );
  inline void introsort( unsigned, unsigned );
public:
  IntroSort();
  ~IntroSort();
  inline void push( istream& );
  void output( ostream& );
  inline void sort();
};
IntroSort::IntroSort()
{size=0;
   v=new unsigned;
}
IntroSort::~IntroSort()
{
  delete[] v;
}
inline void IntroSort::push( istream& in )
{++size;
   v=(unsigned*)realloc( (void*)v, size*sizeof( unsigned ) );
   in>>v[size-1];
}
void IntroSort::output( ostream& out )
{
  for( unsigned i=0; i < size; ++i ) out<<v[i]<<' ';
}
inline void IntroSort::swap( unsigned a, unsigned b )
{unsigned aux=v[a];
   v[a]=v[b];
   v[b]=aux;
}
inline unsigned IntroSort::medianof3( unsigned a, unsigned b, unsigned c )
{
   if( v[a] > v[b] )
   {
      if( v[b] > v[c] )
	return b;
      else if( v[a] > v[c] )
	      return c;
	   else return a;
   }
   else if( v[b] > v[c] )
	{
	   if( v[a] > v[c] )
	     return a;
	   else return c;
	}
   return b;
}
void IntroSort::downheap( unsigned begin, unsigned end )
{
    for( unsigned root=2*begin+1; root < end; )
    {
       if( root+1 < end && v[root] < v[root+1] ) ++root;
       if( v[root] <= v[begin] ) return;
       swap( root, begin );
       begin=root;
       root=2*begin+1;
    }
}
void IntroSort::HeapSort( unsigned begin, unsigned end )
{
     for( unsigned w=end/2-1; w > begin; --w )
	downheap( w, end );
     downheap( begin, end );
     for( end-=1; end > begin; --end )
     {
	swap( begin, end );
	downheap( begin, end );
     }
     swap( begin, end );
     downheap( begin, end );
}
inline void IntroSort::QSort( unsigned left, unsigned right )
{

    if( right > left ) //there are elements
    {
       unsigned sleft=left,pIndex=medianof3( left, left+(right-left)/2+1, left-1 );
       swap( pIndex, right );
       for( unsigned i=left; i < right; ++i )
	  if( v[i] <= v[pIndex] )
	  {
	     swap( i, sleft );
	     ++sleft;
	  }
       swap( sleft, right );
       QSort( left, sleft-1 );
       QSort( sleft+1, right );
    }
}
inline void IntroSort::sort()
{
    QSort( 0, size );
}
int main()
{int N;
 IntroSort a;
   in.open( InFile );
   in>>N;
   while( N-- )
   {

      a.push( in );
   }
   out.open( OutFile );
   a.sort();
   a.output( out );
   return 0;
}