Cod sursa(job #3139268)

Utilizator razviOKPopan Razvan Calin razviOK Data 26 iunie 2023 19:44:34
Problema Radix Sort Scor 0
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.57 kb
#include <stdio.h>
#include <stdlib.h>

typedef struct List{
   unsigned int key;
   struct List *next;
}List;

typedef struct BucketList{
     List *first;
     List *last;
}BucketList;

unsigned int Maximum(unsigned int a,unsigned int b){
    return (a>b) ? a:b;
}
unsigned int MaximumDigits(unsigned int num){

    if(num==0) return 1;

    unsigned int size=0;
    while(num){
        size+=1;
        num/=10;
    }

    return size;
}
BucketList *InsertInList(BucketList *head,unsigned int key){

    if(NULL==head->first)
    {
        head->first=(List *)malloc(sizeof(List));
        head->first->key=key;
        head->first->next=NULL;
        head->last=head->first;
        return head;
    }

    List *temp=(List *)malloc(sizeof(List));
    temp->key=key;
    temp->next=NULL;
    head->last->next=temp;
    head->last=temp;

    return head;
}
BucketList *DeleteFirstInList(BucketList *head){

    if(NULL==head->first)
        return NULL;

    List *temp=head->first;
    head->first=head->first->next;
    temp=NULL;
    free(temp);
    return head;

}
void RadixSort(unsigned long long *arr,unsigned int n,unsigned int maxIterations)
{
   BucketList **bucket=(BucketList **)malloc(sizeof(BucketList *)*10);
   unsigned int div=1,cnt=0;

   for(unsigned int i=0;i<10;i++) {
       bucket[i]=(BucketList * )malloc(sizeof(BucketList));
       bucket[i]->first=NULL;
       bucket[i]->last=NULL;
   }

   for(unsigned int it=0;it<maxIterations;it++) {

       for (unsigned int i = 0; i < n; i++)
           bucket[(arr[i] / div) % 10]=InsertInList(bucket[(arr[i] / div) % 10], arr[i]);

       for (unsigned int i = 0; i < 10; i++) {
           while (NULL != bucket[i]->first) {
               arr[cnt++] = bucket[i]->first->key;
               bucket[i]=DeleteFirstInList(bucket[i]);
           }
       }

       div *= 10;
       cnt = 0;
   }

   for(unsigned int i=0;i<10;i++)
       free(bucket[i]);


}
int main() {

    FILE *f=fopen("radixsort.in","r");
    FILE *g=fopen("radixsort.out","w");

    if(NULL==f || NULL==g)
        exit(1);

    unsigned int n,A,B,C,maxIterations=0;
    fscanf(f,"%u %u %u %u",&n,&A,&B,&C);

    unsigned long long *arr=(unsigned long long *)calloc(n, sizeof(unsigned long long));

    A=A%C;
    B=B%C;
    arr[0]=B;
    for(unsigned int i=1;i<n;i++) {
       // fscanf(f, "%u", &arr[i]);
       arr[i]=((arr[i-1]%C*A)%C+B)%C;
       maxIterations= Maximum(maxIterations, MaximumDigits(arr[i]));
    }
    RadixSort(arr,n,maxIterations);

    for(unsigned int i=0;i<n;i+=10)
        fprintf(g,"%llu ",arr[i]);

    fclose(f);
    fclose(g);
    free(arr);
    return 0;
}