Created
July 8, 2019 13:37
-
-
Save shv07/5caaa0e8a4a9d9169ac17e1a6971476a to your computer and use it in GitHub Desktop.
C code to perform Radix Sort from scratch.
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
# include <stdio.h> | |
# include <stdlib.h> | |
#include <math.h> | |
int A[100]; | |
void print(int n) | |
{ | |
int i; | |
for (i=0;i<n;i++) | |
printf("\n%d",A[i]); | |
} | |
int largest(n) | |
{ | |
int i,max=0; | |
for(i=0;i<n;i++) | |
{ | |
int count=0; | |
int tmp=A[i]; | |
while(tmp!=0) | |
{ | |
count++; | |
tmp=tmp/10; | |
} | |
if(count>max) | |
max=count; | |
} | |
return max; | |
} | |
void countsort(int t, int n) | |
{ | |
int count[10]; int i,digit; int k=0; | |
int B[10][100]; | |
for (i=0;i<10;i++) | |
count[i]=0; | |
for (i=0;i<n;i++) | |
{ | |
digit=(A[i]/t)%10; | |
B[digit][count[digit]]=A[i]; | |
count[digit]++; | |
} | |
for (i=0;i<10;i++) | |
{ | |
if(B[i][0]!=0) | |
{ | |
int j=0; | |
while(B[i][j]!=0) | |
{ | |
A[k]=B[i][j]; | |
j++;k++; | |
} | |
} | |
} | |
} | |
void radix_sort(int n) | |
{ | |
int t,i; | |
t=largest(n); int p=pow(10,t-1); | |
for (i=0;i<t;i++) | |
{ | |
countsort(t,n); | |
t=t/10; | |
} | |
} | |
void main() | |
{ | |
int n,i; | |
scanf("%d",&n); | |
for (i=0;i<n;i++) | |
{ | |
scanf("\n%d",&A[i]); | |
print(n); | |
} | |
radix_sort(n); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment