diff --git a/sorting/radix_sort_3.c b/sorting/radix_sort_3.c new file mode 100644 index 0000000000..fcf6f08443 --- /dev/null +++ b/sorting/radix_sort_3.c @@ -0,0 +1,64 @@ +#include + +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; +} + +void countingSort(int arr[], int n, int exp) { + int output[n]; + int count[10] = {0}; + + for (int i = 0; i < n; i++) { + count[(arr[i] / exp) % 10]++; + } + + for (int i = 1; i < 10; i++) { + count[i] += count[i - 1]; + } + + for (int i = n - 1; i >= 0; i--) { + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + count[(arr[i] / exp) % 10]--; + } + + for (int i = 0; i < n; i++) { + arr[i] = output[i]; + } +} + +void radixSort(int arr[], int n) { + int max = findMax(arr, n); + + for (int exp = 1; max / exp > 0; exp *= 10) { + countingSort(arr, n, exp); + } +} + +int main() { + int n; + printf("Enter the number of elements: "); + scanf("%d", &n); + + int arr[n]; + + printf("Enter the elements: "); + for (int i = 0; i < n; i++) { + scanf("%d", &arr[i]); + } + + radixSort(arr, n); + + printf("Sorted array: "); + for (int i = 0; i < n; i++) { + printf("%d ", arr[i]); + } + printf("\n"); + + return 0; +}