Skip to content

Instantly share code, notes, and snippets.

@rishi93
Created December 15, 2017 13:37
Show Gist options
  • Select an option

  • Save rishi93/631aa0d2aad192b6d412ad31e6dbaaed to your computer and use it in GitHub Desktop.

Select an option

Save rishi93/631aa0d2aad192b6d412ad31e6dbaaed to your computer and use it in GitHub Desktop.
Radix sort (Implementation in C)
#include <stdio.h>
#define RANGE 9
int getMax(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 countsort(int arr[], int n, int d){
int count[RANGE+1] = {0};
int output[n];
for(int i = 0; i < n; i++){
count[(arr[i]/d)%10] += 1;
}
for(int i = 1; i <= RANGE; i++){
count[i] += count[i-1];
}
for(int i = n-1; i >= 0; i--){
output[count[(arr[i]/d)%10] - 1] = arr[i];
count[(arr[i]/d)%10] -= 1;
}
for(int i = 0; i < n; i++){
arr[i] = output[i];
}
}
void radixsort(int arr[], int n){
int max = getMax(arr, n);
for(int d = 1; max/d > 0; d *= 10){
countsort(arr, n, d);
}
}
int main(){
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
printf("After sorting\n");
for(int i = 0; i < n; i++){
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment