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.

AdvancedAdvanced sortingOrdering

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

ads-lsd-radix-sort.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

2 24 45 66 75 90 170 802
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Apply stable counting sort to digits from least to most significant.
  3. 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.