ADVANCED DATA STRUCTURES PROGRAM • LEVEL 12 — ADVANCED SORTING
Perform Stable Counting Sort
Learn how to perform stable counting sort using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
1 2 2 3 3 4 8
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[] = {4, 2, 2, 8, 3, 3, 1}, count[9] = {0}, output[7];
for (int i = 0; i < 7; i++) count[values[i]]++;
for (int i = 1; i < 9; i++) count[i] += count[i - 1];
for (int i = 6; i >= 0; i--) output[--count[values[i]]] = values[i];
print_values(output, 7); return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
1 2 2 3 3 4 8
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Use cumulative frequencies and place elements from right to left to preserve equal-element order.
- Display the computed result.
Use cumulative frequencies and place elements from right to left to preserve equal-element order.
EFFICIENCY
Time and space complexity
Time complexity
O(n + k)
Auxiliary space
O(n + k)
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.
