TheAlgorithms-C/sorting/radix_sort.c

72 lines
1.4 KiB
C
Raw Normal View History

#include <stdio.h>
2018-10-02 07:26:10 +03:00
int largest(int a[], int n)
{
int large = a[0], i;
for (i = 1; i < n; i++)
2018-10-02 07:26:10 +03:00
{
if (large < a[i])
2018-10-02 07:26:10 +03:00
large = a[i];
}
return large;
}
void RadixSort(int a[], int n)
{
int bucket[10][10], bucket_count[10];
int i, j, k, remainder, NOP = 0, divisor = 1, large, pass;
2018-10-02 07:26:10 +03:00
large = largest(a, n);
printf("The large element %d\n", large);
while (large > 0)
2018-10-02 07:26:10 +03:00
{
NOP++;
large /= 10;
2018-10-02 07:26:10 +03:00
}
for (pass = 0; pass < NOP; pass++)
2018-10-02 07:26:10 +03:00
{
for (i = 0; i < 10; i++)
2018-10-02 07:26:10 +03:00
{
bucket_count[i] = 0;
}
for (i = 0; i < n; i++)
2018-10-02 07:26:10 +03:00
{
remainder = (a[i] / divisor) % 10;
bucket[remainder][bucket_count[remainder]] = a[i];
bucket_count[remainder] += 1;
}
2018-10-02 07:26:10 +03:00
i = 0;
for (k = 0; k < 10; k++)
2018-10-02 07:26:10 +03:00
{
for (j = 0; j < bucket_count[k]; j++)
2018-10-02 07:26:10 +03:00
{
a[i] = bucket[k][j];
i++;
}
}
divisor *= 10;
for (i = 0; i < n; i++) printf("%d ", a[i]);
2018-10-02 07:26:10 +03:00
printf("\n");
}
}
2018-10-02 07:26:10 +03:00
int main()
{
int i, n, a[10];
printf("Enter the number of elements :: ");
scanf("%d", &n);
2018-10-02 07:26:10 +03:00
printf("Enter the elements :: ");
for (i = 0; i < n; i++)
2018-10-02 07:26:10 +03:00
{
scanf("%d", &a[i]);
2018-10-02 07:26:10 +03:00
}
RadixSort(a, n);
2018-10-02 07:26:10 +03:00
printf("The sorted elements are :: ");
for (i = 0; i < n; i++) printf("%d ", a[i]);
2018-10-02 07:26:10 +03:00
printf("\n");
return 0;
}