#include <stdio.h>
// Function to find the maximum element in an array
int findMax(int arr[], int n) {
int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
// Function to perform counting sort on the given array based on digit represented by exp
void countingSort(int arr[], int n, int exp) {
const int RANGE = 10;
int output[n];
int count[RANGE] = {0};
// Count occurrences of digits at the current place value
for (int i = 0; i < n; i++) {
count[(arr[i] / exp) % RANGE]++;
}
// Update count[i] to store the position of the current digit in output[]
for (int i = 1; i < RANGE; i++) {
count[i] += count[i - 1];
}
// Build the output array
for (int i = n - 1; i >= 0; i--) {
output[count[(arr[i] / exp) % RANGE] - 1] = arr[i];
count[(arr[i] / exp) % RANGE]--;
}
// Copy the output array to arr[], so that arr[] contains sorted numbers
for (int i = 0; i < n; i++) {
arr[i] = output[i];
}
}
// Main function to implement radix sort on the given array
void radixSort(int arr[], int n) {
// Find the maximum number to know the number of digits
int max = findMax(arr, n);
// Perform counting sort for every digit place
for (int exp = 1; max / exp > 0; exp *= 10) {
countingSort(arr, n, exp);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Driver program to test the radixSort function
int main() {
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
printArray(arr, n);
radixSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}