//
// sort_.cpp
// Sort
//
// Created by ljpc on 2018/4/20.
// Copyright © 2018年 ljpc. All rights reserved.
//
#include "sort_.h"
void print_array(int *arr, int n)
// 打印数组
{
if(n==0){
printf("ERROR: Array length is ZERO\n");
return;
}
printf("%d", arr[0]);
for (int i=1; i<n; i++) {
printf(" %d", arr[i]);
}
printf("\n");
}
int* sort_array(int *arr, int n)
// 编程实现《桶排序算法》
// 函数参数:乱序整数数组 数组长度
// 函数返回值:返回从小到大排序后的数组
{
// 请在这里补充代码,完成本关任务
int max_value = 0; // 数组最大值
for(int i = 0;i < n;i ++ )
max_value = max(max_value,arr[i]);
int bucket_size = 1;
while(max_value)
{
max_value /= 10;
bucket_size *= 10;
}
bucket_size /= 10; // 桶的大小
int bucket[bucket_size][12]; // 桶
int cnt[bucket_size]; // 每个桶存储数据的个数
for(int i = 0;i < bucket_size;i ++ )
cnt[i] = 0;
for(int i = 0;i < n;i ++ )
{
int idx = arr[i] / bucket_size; // 找到数据映射的桶的下标
bucket[idx][cnt[idx] ++ ] = arr[i];
for(int j = cnt[idx] - 1;j > 0;j -- ) // 插入排序
if(bucket[idx][j - 1] > bucket[idx][j])
swap(bucket[idx][j - 1],bucket[idx][j]);
}
int k = 0;
for(int i = 0;i < bucket_size;i ++ )
for(int j = 0;j < cnt[i];j ++ )
arr[k ++ ] = bucket[i][j];
return arr;
/********** End **********/
}
05-15
1768
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-04
325
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-15
871
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-15
570
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-15
568
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-15
782
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-15
786
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交