Cod sursa(job #1266141)

Utilizator thinkphpAdrian Statescu thinkphp Data 18 noiembrie 2014 12:52:59
Problema Sortare prin comparare Scor 20
Compilator c Status done
Runda Arhiva educationala Marime 1.38 kb
/**
 *  @title
 *  Counting Sort Algorithm
 *  
 *  @Description
 *  Counting sort assumes that each of elements is an integer in the range 0 to k, for some integer k
 *
 *  @Reference
 *  http://www.ccodechamp.com/c-program-for-counting-sort-algorithm/
 *  http://www.personal.kent.edu/~rmuhamma/Algorithms/MyAlgorithms/Sorting/countingSort.htm
 */

#include <stdio.h>
#define FIN "algsort.in"
#define FOUT "algsort.out"
#define MAXN 500005

int arr[ MAXN ],
    B[ MAXN ], 
    C[ MAXN ],
    n, max = -1;

void read() {

     int i;

     freopen(FIN, "r", stdin);

     scanf("%d", &n);

     for(i = 1; i <= n; i++) { 
             scanf("%d", &arr[ i ]);
             if(arr[i] > max) max = arr[i];
     }

     fclose( stdin ); 
};

void write() {

     int i;  

     freopen(FOUT, "w", stdout);

     for(i = 1; i <= n; i++) printf("%d ", C[ i ]);

     fclose( stdout ); 

};

void sort() {

     int i,
         j,
         k, 
         f;

     //first loop
     for(i = 0; i <= max; i++) B[ i ] = 0;

     //second loop
     for(j = 1; j <= n; j++) B[ arr[ j ] ]++;

     //third loop
     for(k = 1; k <= max; k++) B[ k ] = B[ k - 1 ] + B[ k ];

     //final loop
     for(f = n; f >= 1; f--) C[ B[ arr[f] ] ] = arr[ f ], B[ arr[f] ] = B[ arr[f] ] - 1;
};

int main() {

    read();
    sort();
    write();

    return(0);
}