用Java完成桶排序
时间: 2023-07-01 20:10:09 浏览: 60
好的,以下是Java实现桶排序的示例代码:
```java
public class BucketSort {
public static void bucketSort(int[] array, int bucketSize) {
if (array.length == 0) {
return;
}
//确定最大值和最小值
int minValue = array[0];
int maxValue = array[0];
for (int i = 1; i < array.length; i++) {
if (array[i] < minValue) {
minValue = array[i];
} else if (array[i] > maxValue) {
maxValue = array[i];
}
}
//计算桶的数量
int bucketCount = (maxValue - minValue) / bucketSize + 1;
ArrayList<ArrayList<Integer>> buckets = new ArrayList<>(bucketCount);
for (int i = 0; i < bucketCount; i++) {
buckets.add(new ArrayList<Integer>());
}
//将每个元素放入相应的桶中
for (int i = 0; i < array.length; i++) {
int bucketIndex = (array[i] - minValue) / bucketSize;
buckets.get(bucketIndex).add(array[i]);
}
//对每个桶中的元素进行排序
for (int i = 0; i < buckets.size(); i++) {
ArrayList<Integer> bucket = buckets.get(i);
Collections.sort(bucket);
}
//将桶中的元素依次取出
int index = 0;
for (ArrayList<Integer> bucket : buckets) {
for (int value : bucket) {
array[index++] = value;
}
}
}
}
```
使用示例:
```java
int[] array = {5, 3, 2, 8, 7, 2, 1, 0, 9, 6};
BucketSort.bucketSort(array, 3);
System.out.println(Arrays.toString(array)); //输出[0, 1, 2, 2, 3, 5, 6, 7, 8, 9]
```
在这个示例中,我们使用桶大小为3进行排序。您可以根据需要将其更改为其他值。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](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)
![](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)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)