Java 写一个桶排序
时间: 2023-05-12 22:06:25 浏览: 81
Java 中桶排序的代码实现如下:
```
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BucketSort {
public static void sort(int[] arr) {
int maxValue = Integer.MIN_VALUE;
for (int value : arr) {
maxValue = Math.max(maxValue, value);
}
List<List<Integer>> buckets = new ArrayList<>();
for (int i = 0; i <= maxValue; i++) {
buckets.add(new ArrayList<>());
}
for (int value : arr) {
buckets.get(value).add(value);
}
int index = 0;
for (List<Integer> bucket : buckets) {
Collections.sort(bucket);
for (int value : bucket) {
arr[index++] = value;
}
}
}
public static void main(String[] args) {
int[] arr = new int[]{4, 2, 9, 6, 23, 12, 34, 0, 1};
sort(arr);
for (int value : arr) {
System.out.print(value + " ");
}
}
}
```
阅读全文