class Yao{ public: char bh[10]; char name[30]; int danjia; int shuliang; int xiaoshou; void dayin(){ printf("%10s %10s %10d %10d %10d\n",bh,name,danjia,shuliang,xiaoshou); } }; Yao yao[1000]; int num = 0;采用基数排序,对yao数组按照元素的bh属性进行排序
时间: 2023-12-10 15:42:06 浏览: 31
以下是基数排序的实现代码:
```
void radixSort(Yao arr[], int n) {
// 找到最大的bh长度
int maxLen = strlen(arr[0].bh);
for (int i = 1; i < n; i++) {
int len = strlen(arr[i].bh);
if (len > maxLen) {
maxLen = len;
}
}
// 对每一位进行排序
for (int i = maxLen - 1; i >= 0; i--) {
// 计算每个桶中元素的个数
int count[10] = {0};
for (int j = 0; j < n; j++) {
int digit = (i < strlen(arr[j].bh)) ? (arr[j].bh[i] - '0') : 0;
count[digit]++;
}
// 计算每个桶中元素的位置
int position[10] = {0};
for (int j = 1; j < 10; j++) {
position[j] = position[j - 1] + count[j - 1];
}
// 将元素按照当前位放入桶中
Yao temp[n];
for (int j = 0; j < n; j++) {
int digit = (i < strlen(arr[j].bh)) ? (arr[j].bh[i] - '0') : 0;
temp[position[digit]] = arr[j];
position[digit]++;
}
// 将排序后的元素复制回原数组
for (int j = 0; j < n; j++) {
arr[j] = temp[j];
}
}
}
```
调用方式:
```
radixSort(yao, num);
```
说明:该基数排序的时间复杂度为 O(d*(n+k)),其中 d 为最大的 bh 长度,k 为每一个桶中元素的个数(在该代码中固定为 10)。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![sln](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)