赞
踩
桶排序是一种基于计数的排序算法,它的核心思想是将待排序的元素分到不同的桶中,然后对每个桶中的元素进行排序,最后将所有桶中的元素依次取出来就得到了有序的结果。
具体的实现步骤如下:
- public class BucketSort {
- public static void bucketSort(int[] arr, int bucketSize) {
- if (arr.length == 0) {
- return;
- }
-
- // 找到数组中的最大值和最小值
- int max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
- for(int i:arr){
- max=Math.max(max,i);
- min=Math.min(min,i);
- }
-
- // 计算桶的个数
- int bucketCount = (max - min) / bucketSize + 1;
- List<List<Integer>> buckets = new ArrayList<>(bucketCount);
- for (int i = 0; i < bucketCount; i++) {
- buckets.add(new ArrayList<>());
- }
-
- // 将元素放入桶中
- for (int i = 0; i < arr.length; i++) {
- int bucketIndex = (arr[i] - min) / bucketSize;
- buckets.get(bucketIndex).add(arr[i]);
- }
-
- // 对每个桶中的元素进行排序
- for (List<Integer> bucket : buckets) {
- Collections.sort(bucket);
- }
-
- // 将排序后的结果放入原数组中
- int index = 0;
- for (List<Integer> bucket : buckets) {
- for (int num : bucket) {
- arr[index++] = num;
- }
- }
- }
-
- public static void main(String[] args) {
- int[] arr = { 5, 2, 9, 1, 4, 6, 3, 8, 7 };
- bucketSort(arr, 3);
- System.out.println(Arrays.toString(arr));
- }
- }
-
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。