【问题标题】:Sorting an array using Bucket Sort [duplicate]使用桶排序对数组进行排序[重复]
【发布时间】:2021-11-04 14:30:39
【问题描述】:

我想使用桶排序对这个数组 = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2} 进行排序。我的代码中出现 arrayindexoutofboundsexception 错误。有人可以帮我更正我的代码吗...

package com.bucketsort;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        int[] arr = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2};

        System.out.println("Unsorted: " + Arrays.toString(arr));

        bucketSort(arr);
        System.out.println("Sorted  :  " + Arrays.toString(arr));
    }

    public static int[] bucketSort(int[] arr) {
        int max = getMax(arr);
        int[] sortedArray = new int[max + 1];

        //loop and place n at nth position
        for (int cur : arr) {
            for (int i = 0; i <= max; i++) {
                int currentVal = arr[i];
                sortedArray[currentVal] = currentVal;
            }
        }
        return sortedArray;
    }

    //method to get the maximum value
    public static int getMax(int[] arr) {
        int maxValue = arr[0];
        for(int i=1;i<arr.length;i++) {
            if(arr[i] > maxValue) {
                maxValue = arr[i];
            }
        }
        return maxValue;
    }
}

这是我运行此代码时得到的屏幕截图。

【问题讨论】:

    标签: java algorithm sorting bucket-sort


    【解决方案1】:

    问题从这里开始:

        for (int i = 0; i <= max; i++) {
            int currentVal = arr[i];
            sortedArray[currentVal] = currentVal;
        }
    

    因为您从 getMax 函数返回值而不是索引。

    【讨论】:

      【解决方案2】:

      这里的问题是你的这部分代码,你从 0 循环到最大 arr 其长度固定为 15 并且在最大值之前

              for (int cur : arr) {
                  for (int i = 0; i <= max; i++) { <---
                      int currentVal = arr[i]; <---
                      sortedArray[currentVal] = currentVal;
                  }
              }
      

      ,只需删除它并使用以下内容:

              for (int cur : arr) {
                  sortedArray[curr] = curr;
              }
      

      【讨论】:

        猜你喜欢
        • 2021-07-25
        • 2020-05-17
        • 1970-01-01
        • 1970-01-01
        • 2013-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多