Search code examples
javafor-loopbubble-sort

Ascending Order Bubble sort java.lang.ArrayIndexOutOfBoundsException: 5 at wst2.calc(wst2.java:18)


This is the program that I have made and I even did a proper for loop starting from 0 to 4 as 5 numbers need to be sorted , Still getting arrayindexoutofboundsexception.

import java.util.*; class wst2 {
    public static void calc()
    {
        Scanner sc= new Scanner(System.in);
        int i,j , temp;
        int a[]=new int [5];
        for(i=0;i<=4;i++)
        {
            System.out.println("Enter 5 numbers");
            a[i]=sc.nextInt();
        }
        for(i=0;i<=4;i++)
        {
            for(j=i;j<=4-i;j++)
            { 
                if(a[j] > a[j+1])
                {
                    temp=a[j];
                    a[j]=a[j+1];
                    a[j+1]=temp;
                }
            }
        }
        for(i=0;i<=4;i++)
        {
            System.out.println(a[i]);
        }
    } }

Solution

  • This statement int a[]=new int [5]; defines an array with length of 5. With an array of length 5, you can access elements with indices form 0 to 4 ({0, 1, 2, 3, 4}). But at this line

    a[j]=a[j+1];
    

    in a possible and particular condition (j = 4 and i = 0), you are trying to access to the a[4+1] (means a[5]) which is not allowed.