当前位置:   article > 正文

排序算法-桶排序

排序算法-桶排序

   桶排序是一种基于计数的排序算法,它的核心思想是将待排序的元素分到不同的桶中,然后对每个桶中的元素进行排序,最后将所有桶中的元素依次取出来就得到了有序的结果。

具体的实现步骤如下:

  1. 创建一个固定大小的桶数组,每个桶都是一个容器,用来存放元素。
  2. 遍历待排序的数组,将每个元素根据一定的规则分配到对应的桶中。这个规则可以是简单的映射关系,例如元素除以桶的个数取整,或者根据元素的大小将其放入不同的桶中。
  3. 对每个非空的桶进行排序,可以使用任何一种排序算法,例如插入排序、快速排序等。
  4. 将所有桶中的元素依次取出来,就得到了有序的结果。
  1. public class BucketSort {
  2. public static void bucketSort(int[] arr, int bucketSize) {
  3. if (arr.length == 0) {
  4. return;
  5. }
  6. // 找到数组中的最大值和最小值
  7. int max=Integer.MIN_VALUE,min=Integer.MAX_VALUE;
  8. for(int i:arr){
  9. max=Math.max(max,i);
  10. min=Math.min(min,i);
  11. }
  12. // 计算桶的个数
  13. int bucketCount = (max - min) / bucketSize + 1;
  14. List<List<Integer>> buckets = new ArrayList<>(bucketCount);
  15. for (int i = 0; i < bucketCount; i++) {
  16. buckets.add(new ArrayList<>());
  17. }
  18. // 将元素放入桶中
  19. for (int i = 0; i < arr.length; i++) {
  20. int bucketIndex = (arr[i] - min) / bucketSize;
  21. buckets.get(bucketIndex).add(arr[i]);
  22. }
  23. // 对每个桶中的元素进行排序
  24. for (List<Integer> bucket : buckets) {
  25. Collections.sort(bucket);
  26. }
  27. // 将排序后的结果放入原数组中
  28. int index = 0;
  29. for (List<Integer> bucket : buckets) {
  30. for (int num : bucket) {
  31. arr[index++] = num;
  32. }
  33. }
  34. }
  35. public static void main(String[] args) {
  36. int[] arr = { 5, 2, 9, 1, 4, 6, 3, 8, 7 };
  37. bucketSort(arr, 3);
  38. System.out.println(Arrays.toString(arr));
  39. }
  40. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/415594
推荐阅读
相关标签
  

闽ICP备14008679号