Cod sursa(job #3326619)

Utilizator calinulCalin Cernat calinul Data 29 noiembrie 2025 17:29:58
Problema Sortare prin comparare Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <stdio.h>
#include <ctype.h>

#define NMAX 500000

int v[NMAX];

FILE *fin, *fout;

int rInt() {
  int rez = 0, ch;
  while ( !isdigit( ch = fgetc( fin ) ) );
  do
    rez = rez * 10 + ch - '0';
  while ( isdigit( ch = fgetc( fin ) ) );
  return rez;
}

void wInt( int x ) {
  int cf[11], i = 0;
  do {
    cf[i++] = x % 10;
    x /= 10;
  } while ( x > 0 );
  for ( i = i - 1; i >= 0; i-- )
    fputc( cf[i] + '0', fout );
  fputc( ' ', fout );
}

static inline void swap( int *a, int *b ) {
  int aux = *a;
  *a = *b;
  *b = aux;
}

void qSort( int v[], int begin, int end ) {
  int b = begin - 1, e = end + 1, p = v[(begin + end) / 2];

  while ( v[++b] < p );
  while ( v[--e] > p );

  while ( b < e ) {
    swap( &v[b], &v[e] );

    while ( v[++b] < p );
    while ( v[--e] > p );
  }

  if ( begin < e )
    qSort( v, begin, e );
  if ( e + 1 < end )
    qSort( v, e + 1, end );
}

int main() {
  int n, i;

  fin = fopen( "algsort.in", "r" );
  n = rInt();
  for ( i = 0; i < n; i++ )
    v[i] = rInt();
  fclose( fin );

  qSort( v, 0, n - 1 );

  fout = fopen( "algsort.out", "w" );
  for ( i = 0; i < n; i++ )
    wInt( v[i] );
  fputc( '\n', fout );
  fclose( fout );

  return 0;
}