【发布时间】: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