Skip to content

Commit

Permalink
Create radix_sort_3.c
Browse files Browse the repository at this point in the history
  • Loading branch information
debnath003 authored Oct 1, 2023
1 parent e5dad3f commit 4a59273
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions sorting/radix_sort_3.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#include <stdio.h>

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;
}

0 comments on commit 4a59273

Please sign in to comment.