Cod sursa(job #2670130)

Utilizator LucaMihaiLM10Luca Ilie LucaMihaiLM10 Data 9 noiembrie 2020 09:20:10
Problema Statistici de ordine Scor 100
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <stdio.h>
#include <ctype.h>
#define NMAX 3000000
int v[NMAX];
int readInt( FILE *fin ) {
    int n;
    char ch;
    ch = fgetc( fin );
    while ( isdigit( ch ) == 0 )
        ch = fgetc( fin );
    n = 0;
    while ( isdigit( ch ) ) {
        n = n * 10 + ch - '0';
        ch = fgetc( fin );
    }
    return n;
}
int main() {
    FILE *fin, *fout;
    int n, k, p, beg, end, b, e, aux, i;
    fin = fopen( "sdo.in", "r" );
    fscanf( fin, "%d %d", &n, &k );
    for ( i = 0; i < n; i++ )
        v[i] = readInt( fin );
    fclose( fin );
    k--;
    beg = 0;
    end = n - 1;
    while ( beg < end ) {
        b = beg;
        e = end;
        p = v[(beg + end) / 2];
        while ( v[b] < p )
            b++;
        while ( v[e] > p )
            e--;
        while ( b < e ) {
            while ( b < e ) {
                aux = v[b];
                v[b] = v[e];
                v[e] = aux;
                do
                    b++;
                while ( v[b] < p );
                do
                    e--;
                while ( v[e] > p );
            }
        }
        if ( k <= e )
            end = e;
        else
            beg = e + 1;
    }
    fout = fopen( "sdo.out", "w" );
    fprintf( fout, "%d", v[k] );
    fclose( fout );
    return 0;
}