-
-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
e5dad3f
commit 4a59273
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |