Cod sursa(job #3177529)

Utilizator Andrei_Gagea08Andrei Gagea Andrei_Gagea08 Data 29 noiembrie 2023 12:47:36
Problema Radix Sort Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <stdio.h>
#include <string.h>

#define MAX_N 10000000
#define MAX_BITS 32
#define BITS_PER_STEP 8
const int BASE = (1 << BITS_PER_STEP);
const int MASK = BASE - 1;

// Avem nevoie de un array auxiliar, pentru a aranja numerele dupa fiecare pas al algoritmului
int v1[MAX_N], v2[MAX_N];
int freq[BASE], ind[BASE];

void sort(int v[], int aux[], int n, int bits) {
  if (bits == MAX_BITS)
    return;

  memset(freq, 0, sizeof(freq));

  int i;
  for (i = 0; i < n; ++i)
    ++freq[v[i] >> bits & MASK];

  ind[0] = 0;
  for (i = 1; i < BASE; ++i)
    ind[i] = ind[i - 1] + freq[i - 1];

  for (i = 0; i < n; ++i)
    aux[ind[v[i] >> bits & MASK]++] = v[i];

  // Interschimbare intre vectorul aux si v
  sort(aux, v, n, bits + BITS_PER_STEP);
}

int main() {
  FILE* fin = fopen("algsort.in", "r");
  int n, i;
  fscanf(fin, "%d", &n);
  for (i = 0; i < n; ++i)
    fscanf(fin, "%d", &v1[i]);
  fclose(fin);

  sort(v1, v2, n, 0);

  FILE* fout = fopen("algsort.out", "w");
  for (i = 0; i < n; ++i)
    fprintf(fout, "%d ", v1[i]);
  fclose(fout);
  return 0;
}