I want to sort this array = {20, 46, 22, 19, 6, 42, 14, 5, 48, 47, 17, 39, 51, 7, 2} using bucket sort. I get a arrayindexoutofboundsexception error in my code. Can someone please help me to correct my code...
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;
}
}
This is a screenshot of what I get when i run this code.