ADVANCED DATA STRUCTURES PROGRAM • LEVEL 12 — ADVANCED SORTING
Sort Integers with LSD Radix Sort
Learn how to sort integers with lsd radix sort using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
2 24 45 66 75 90 170 802
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
void print_values(const int values[], int count) { for (int i = 0; i < count; i++) printf("%d%c", values[i], i == count - 1 ? '\n' : ' '); }
int main(void)
{
int values[] = {170, 45, 75, 90, 802, 24, 2, 66};
for (int exponent = 1; 802 / exponent > 0; exponent *= 10) {
int count[10] = {0}, output[8];
for (int i = 0; i < 8; i++) count[(values[i] / exponent) % 10]++;
for (int i = 1; i < 10; i++) count[i] += count[i - 1];
for (int i = 7; i >= 0; i--) output[--count[(values[i] / exponent) % 10]] = values[i];
for (int i = 0; i < 8; i++) values[i] = output[i];
}
print_values(values, 8); return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
2 24 45 66 75 90 170 802
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Apply stable counting sort to digits from least to most significant.
- Display the computed result.
Apply stable counting sort to digits from least to most significant.
EFFICIENCY
Time and space complexity
Time complexity
O(d(n + b))
Auxiliary space
O(n + b)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
