-1

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.

enter image description here

RaVeN
  • 33
  • 1
  • 7

2 Answers2

0

The problem starts here:

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

Since you are returning the value from the getMax function instead of index.

Papai from BEKOAIL
  • 1,469
  • 1
  • 11
  • 17
0

The problem here is this part of your code, you loop from the 0 to max for the arr which its length fixed 15 and before the max

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

, Just remove that and use the following:

        for (int cur : arr) {
            sortedArray[curr] = curr;
        }
0xh3xa
  • 4,801
  • 2
  • 14
  • 28