#include <iostream>
using namespace std;
int findMax(int arr[], int len) {
int max = arr[0];
for (int i = 1; i < len; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}
int calBitCount(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 /= 10;
}
return value % 10;
}
void radixSort(int arr[], int len) {
int max = findMax(arr, len);
int bitCount = calBitCount(max);
int radixCount = 10;
int* count = new int[radixCount]();
int *tempArray = new int[len]();
for (int b = 0; b < bitCount; ++b) {
fill(count, count + radixCount, 0);
for (int i = 0; i < len; ++i) {
int bitValue = getBitValue(arr[i], b);
count[bitValue]++;
}
for (int c = 1; c < radixCount; ++c) {
count[c] += count[c - 1];
}
for (int i = len - 1; i >= 0; --i) {
int bitValue = getBitValue(arr[i], b);
tempArray[count[bitValue] - 1] = arr[i];
count[bitValue]--;
}
copy(tempArray, tempArray + len, arr);
}
delete[] count;
delete[] tempArray;
}
void printArray(int arr[], int len) {
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {17, 45, 75, 90, 42, 24, 2, 66};
int len = sizeof(arr) / sizeof(arr[0]);
cout << "原始数组:" << endl;
printArray(arr, len);
radixSort(arr, len);
cout << "排序后的数组:" << endl;
printArray(arr, len);
return 0;
}