Cod sursa(job #2679944)

Utilizator teochess2017Togan Teodor-Bogdan teochess2017 Data 1 decembrie 2020 23:48:39
Problema Sortare prin comparare Scor 20
Compilator c-64 Status done
Runda Arhiva educationala Marime 1.66 kb
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define GRUP 100000
#define MAXN 500000
#define MAXNR 2147483647
#define MAXFRECV (MAXNR / GRUP + 1)

int v[MAXN], frecv[MAXFRECV], auxv[MAXN];

FILE *fin, *fout;

int readInt(){
  int n;
  char ch;
  while(!isdigit(ch = fgetc(fin)));
  n = ch - '0';
  while(isdigit(ch = fgetc(fin))){
    n = n * 10 + ch - '0';
  }
  return n;
}
void quicksort(int min, int max){
  int b, e, piv, aux;
  b = min;
  e = max;
  piv = v[(min + max) / 2];
  while(piv > v[b]){
    b++;
  }
  while(piv < v[e]){
    e--;
  }
  while(b < e){
    aux = v[b];
    v[b] = v[e];
    v[e] = aux;
    do{
      b++;
    }while(piv > v[b]);
    do{
      e--;
    }while(piv < v[e]);
  }
  if(min < e){
    quicksort(min, e);
  }
  if((e + 1) < max){
    quicksort(e + 1, max);
  }
}
void bucketsort(int n){
  int i, t, aux;
  for(i = 0; i < n; i++){
    frecv[v[i] / GRUP]++;
  }
  t = frecv[0];
  frecv[0] = 0;
  for(i = 1; i <= MAXFRECV; i++){
    aux = frecv[i];
    frecv[i] = frecv[i - 1] + t;
    t = aux;
  }
  for(i = 0; i < n; i++){
    auxv[frecv[v[i] / GRUP]++] = v[i];
  }
  t = 0;
  for(i = 1; i < n; i++){
    v[i] = auxv[i];
    if((v[i] / GRUP) != (v[i - 1] / GRUP)){
      quicksort(t, i - 1);
      t = i;
    }
  }
  quicksort(t, i - 1);
}
int main()
{
    int n, i;
    fin = fopen("algsort.in", "r");
    n = readInt();
    for(i = 0; i < n; i++){
      v[i] = readInt();
    }
    fclose(fin);
    bucketsort(n);
    fout = fopen("algsort.out", "w");
    for(i = 0; i < n; i++){
      fprintf(fout, "%d ", v[i]);
    }
    fclose(fout);
    return 0;
}