Search code examples
arrayssortingradix

Radix Sort (Why am I getting ArrayIndexOutOfBoundsException line:43)


I have given a time to this algorithm but still can't figure out where am I doing something wrong. Can anyone help me with my logic on "Radix Sort", if I am doing right with the following code then please help my figure out why am I getting the ArrayIndexOutOfBoundsException at line:arr[sortedIndex] = tempArray[j][k];

    int[] arr = {3,10,50,137,90,139,40};
    int maxValue = arr[0], sortedIndex = 0, mode = 10, n = 1;

    // Displays unsorted array
    for(int i = 0; i < arr.length; i++){
        System.out.print(arr[i] + " ");
    }
    System.out.println("\n");

    // finds maximum digit
    for(int i = 0; i < arr.length; i++){
        if(arr[i] > maxValue){
            maxValue = arr[i];
        }
    }

    // Gets number of digits
    int maxDigits = (String.valueOf(maxValue)).length();

    for(int i = 0; i < maxDigits; i++){
        int[][] tempArray = new int[10][arr.length];

        // Transfers 1-D array value to 2-D array w.r.t baseIndex
        for(int j = 0; j < arr.length; j++){
            int modulus = arr[j] % mode;
            int baseIndex = modulus / n;

            for(int k = 0; k < tempArray[baseIndex].length; k++){
                if(tempArray[baseIndex][k] == 0){
                    tempArray[baseIndex][k] = arr[j];
                    break;
                }
            }
        }

        // Shifts partially sorted array to new array
        for(int j = 0; j < tempArray.length; j++){
            for(int k = 0; k < tempArray[j].length; k++){
                if(tempArray[j][k] > 0){
                    arr[sortedIndex] = tempArray[j][k];
                    sortedIndex++;
                }
            }
        }

        mode *= 10;
        n *= 10;
    }

    // Displays sorted array
    for(int i = 0; i < arr.length; i++){
        System.out.print(arr[i] + " ");
    }

Solution

  • Print the contents of tempArray before you attempt to shift partially sorted array to new array to see what it holds . arr[] can only hold 7 values. tempArray has more than 7 values greater than 0. Therefore, you are attempting to fill the arr[] with more than 7 numbers.