#include<stdio.h>
#include<time.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
int main(){
srand((unsigned int)time(NULL));
int n = 100;
int nums[n];
int buf[n];
for (int i = 0; i < n; ++i) {
nums[i] = rand() % 10000;
}
int maxval = nums[0];
for (int i = 1; i < n; ++i) {
maxval = fmax(maxval, nums[i]);
}
int exp = 1;
while (maxval >= exp) {
int count[10] = {0};
//将每一位数字的一位上的数字进行计数
for (int i = 0; i < n; ++i) {
int temp = (nums[i] / exp) % 10;
count[temp]++;
}
//将序号做记录方便后续的取数操作
for (int i = 1; i < 10; ++i) {
count[i] += count[i - 1];
}
//将排序后的数组取出
for (int i = n - 1; i >= 0; --i) {
int temp = (nums[i] / exp) % 10;
buf[count[temp] - 1] = nums[i];
count[temp]--;
}
memcpy(nums, buf, sizeof(int) * n);
exp *= 10;
}
//打印出数组
for (int i = 0; i < n; ++i) {
printf("%d ", nums[i]);
}
return 0;
}
基排序
最新推荐文章于 2022-05-11 10:15:12 发布