编辑代码

#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;
}

//输入50,返回2
//输入100,返回3 
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);
    //1.计算出来有多少位
    int bitCount = calcBitCount(max);
    int radixCount = 10;
    int *countarray = (int*)malloc(sizeof(int)*(radixCount)); //统计0-9元素
    int *temparray = (int*)malloc(sizeof(int)*(length));
    //2.从低位开始,对每一位进行排序
    for (int i = 0; i < bitCount; i++) {
        //3.1 清空排序数组,把每个值赋予0 
        cleararray(countarray, radixCount);

        //3.2 遍历数组,取出数据当前位对应的值,并进行计数
        for (int j = 0; j < length; j++) {
            int bitValue = getBitValue(Array[j], i);
            ++countarray[bitValue];
        }
        //3.3 对计数进行累加
        for (int c = 0; c < radixCount; c++) {
            countarray[c] = countarray[c] + countarray[c - 1];
        }
        //3.4 利用累加值和临时数组对对应的位进行排序
        for (int j = length - 1; j >= 0; j--) {
            int bitValue = getBitValue(Array[j], i);
            temparray[--countarray[bitValue]] = Array[j];
        }
        
        //3.5 排序好的数组拷贝回给原数组
        for (int j = 0 ; j < length; j++) {
            Array[j] = temparray[j];
        }
    }

    //4.0 释放空间
    free(countarray);
    free(temparray);
}

int main () {
    //JSRUN引擎2.0,支持多达30种语言在线运行,全仿真在线交互输入输出。 
    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;
}