Radix sort in C: solved exercise

Radix sort in C: solved exercise

This exercise is scheduled for daily publication and follows the standard site structure: statement, solution, and expected output.

Problem statement

Solve the practical case and verify the console output.

C solution

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#include <stdio.h>

void count_exp(int a[], int n, int exp) {
    int out[32], c[10] = {0};
    for (int i = 0; i < n; i++) c[(a[i]/exp)%10]++;
    for (int i = 1; i < 10; i++) c[i] += c[i-1];
    for (int i = n-1; i >= 0; i--) out[--c[(a[i]/exp)%10]] = a[i];
    for (int i = 0; i < n; i++) a[i] = out[i];
}

int main(void) {
    int a[] = {170,45,75,90,802,24,2,66};
    int n = (int)(sizeof(a)/sizeof(a[0]));
    for (int exp = 1; exp <= 100; exp *= 10) count_exp(a, n, exp);
    for (int i = 0; i < n; i++) printf("%d ", a[i]);
    printf("\n");
    return 0;
}

Expected output

1
2 24 45 66 75 90 170 802

Common mistakes

  • Not validating standard-function return values.
  • Ignoring edge cases for indices, pointers, or buffers.
  • Skipping example-based test runs before publishing.

Practical use

Radix sort is ideal for sorting fixed-length integers or equal-length strings, such as dates, IDs, or numeric identifiers.

Guided practice and full book

If you want a complete path with progressive difficulty:

FAQ

Is this exercise useful for C exams and technical interviews?

Yes. It targets patterns that commonly appear in practice assignments, technical interviews, and C programming exams.

Where can I keep practicing with more solved C exercises?

In Programming in C in 100 Solved Exercises and C Exercises. Kindle Unlimited: View on Amazon.

How should I practice this exercise type to improve faster?

Start with small inputs, run edge cases (empty, one item, max capacity), then rewrite the solution from scratch without copying.