0

Why am i getting this error ? I am trying to sort from small to greater in the int array and print it but its not working. I am getting this error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 10
        at Bubblesort.bubbleSort(Bubblesort.java:26)
        at Bubblesort.main(Bubblesort.java:47)

Source code:

class Bubblesort {
    
    static String arrayToString(int[] arr){
        for (int i = 0; i < arr.length ; i++ ){ 
        System.out.print(arr[i]);
        System.out.print(",");
        }
        return null;
        
    }
    
    static int[] randomArray(int n) {
        java.util.Random rand = new java.util.Random();
        int[] array = new int[n];
        for (int i = 0; i < n ; i++ ){ 
            int random = rand.nextInt(99);
            array[i] = random;
        }
        return array;   
    }

    
    static void bubbleSort(int[] arr){
        for ( int i = 0; i < arr.length ; i++ ) {
            if ( arr[i] > arr[i+1] ) {
                arr[i] = arr[i+1];
                arr[i+1] = arr[i];
            } else {
                arr[i] = arr[i];    
            }
        }
    }                                 
    


public static void main (String[] args) {

    int[] test10 = randomArray(10);
    int[] test20 = randomArray(20);
    int[] test30 = randomArray(30);
    
    arrayToString(test10);
    System.out.println("");
    arrayToString(test20);
    System.out.println("");
    arrayToString(test30);
    System.out.println("");
    

    bubbleSort(test10);
    arrayToString(test10);
    System.out.println("");
    
    
    
    }
1
  • In your bubblesort function you are trying to compare to arr[i+1] Commented Apr 17, 2021 at 16:26

1 Answer 1

1

Your array has ten elements, indexed from 0 to 9.

In the for loop inside your bubblesort function, you iterate over all these elements, letting i go from zero to nine.

The first thing you do here is compare arr[i] and arr[i+1]. When i is nine, that means you're trying to compare arr[9] to arr[10]. But there is no such thing as arr[10]. Your array index is out of bounds, hence the ArrayIndexOutOfBoundsException.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.