编辑代码

#include <stdio.h>
#include <stdlib.h>

//找出数组的最大值
int findMax(int arr[], int len) {
    int max = arr[0];
    for(int i = 0; i < len; i++) {
        if (arr[i] > max) {
            max = arr[i];
        }
    }
    return max;
}

//计算数组元素的位数
int calcBitCount(int arr[], int len) {
    //找出数组的最大值
    int max = findMax(arr, len);
    int bitCount = 1;
    while((max = max/10) > 0) {//不断将max除以10,直到它小于10为止
        ++bitCount;//每除以一次10,就将位数加1
    }
    return bitCount;
}

//将数组中的元素全部清零
void clearArray(int arr[], int len) {
    for (int i = 0; i < len; i++) {
        arr[i] = 0;
    }
}

//获取value从右往左数第bit位的值
int getCurrentBitValue(int value, int bit) {
    for(int i = 0; i < bit; ++i) {
        value = value / 10;//不断将value除以10,直到它的右边bit位变成最后一位 
    }

    return value % 10;
}

void radixSort(int arr[], int len) {
    //1.计算出来有多少位
    int bitCount = calcBitCount(arr, len);
    int radixCount = 10;
    int *countArray = (int*)malloc(sizeof(int)*(radixCount)); //统计0-9元素
    int *tempArray = (int*)malloc(sizeof(int)*(len));
    //2.从低位开始,对每一位进行排序
    for (int i = 0; i < bitCount; i++) {
        clearArray(countArray, radixCount);

        //2.1 遍历数组,取出数据当前位对应的值,并进行计数
        for (int j = 0; j < len; j++) {
            int bitValue = getCurrentBitValue(arr[j], i);
            ++countArray[bitValue];//对当前位的值进行计数
        }
        //2.2 对计数进行累加
        for (int c = 0; c < radixCount; c++) {
            //将前面所有元素的计数值加起来
            countArray[c] = countArray[c] + countArray[c - 1];
        }
        //2.3 基于累计值进行计数排序,排序结果放到tempArray
        for (int j = len - 1; j >= 0; j--) {
            int bitValue = getCurrentBitValue(arr[j], i);
            tempArray[--countArray[bitValue]] = arr[j];//按照当前位的值从大到小排序
        }
        
        //2.4 排序好的数组拷贝回给arr
        for (int j = 0 ; j < len; j++) {
            arr[j] = tempArray[j];
        }
    }

    //3.释放内存
    free(countArray);
    free(tempArray);
}

void printArray(int arr[], int len) {
    for(int i = 0; i < len; i++) {
        printf("%4d",arr[i]);
    }
    printf("\n");
}

int main () {
    int arr1[] = {70, 45, 75, 90, 82, 24, 2, 66};
    int length1 = sizeof(arr1) / sizeof(arr1[0]);
    printArray(arr1,length1);
    radixSort(arr1, length1);
    printf("排序后的数组:\n");
    printArray(arr1,length1);
    return 0;
}