#include <stdio.h>
#include <stdlib.h>
void display(char str[], int Array[], int length){
printf("%s", str);
for(int i = 0; i < length; i++)
printf("%d ", Array[i]);
printf("\n");
}
int findMax(int Array[], int length){
int max = Array[0];
for(int i = 0; i < length; i++){
if(max < Array[i])
max = Array[i];
}
return max;
}
int calcBitCount(int max) {
int count = 0;
while(max != 0){
max /= 10;
count++;
}
return count;
}
int getBitValue(int value, int bit) {
for(int i = 0; i < bit; ++i) {
value = value / 10;
}
return value % 10;
}
void cleararray(int Array[], int length) {
for (int i = 0; i < length; i++) {
Array[i] = 0;
}
}
void radixSort(int Array[], int length){
int max = findMax(Array, length);
int bitCount = calcBitCount(max);
int radixCount = 10;
int *countarray = (int*)malloc(sizeof(int)*(radixCount));
int *temparray = (int*)malloc(sizeof(int)*(length));
for (int i = 0; i < bitCount; i++) {
cleararray(countarray, radixCount);
for (int j = 0; j < length; j++) {
int bitValue = getBitValue(Array[j], i);
++countarray[bitValue];
}
for (int c = 0; c < radixCount; c++) {
countarray[c] = countarray[c] + countarray[c - 1];
}
for (int j = length - 1; j >= 0; j--) {
int bitValue = getBitValue(Array[j], i);
temparray[--countarray[bitValue]] = Array[j];
}
for (int j = 0 ; j < length; j++) {
Array[j] = temparray[j];
}
}
free(countarray);
free(temparray);
}
int main () {
int Array[] = {70, 45, 75, 90, 82, 24, 2, 66};
int length = sizeof(Array)/sizeof(*Array);
display("排序前:",Array,length);
radixSort(Array, length);
display("排序后:",Array,length);
return 0;
}