Aleks
Aleks

Reputation: 111

Bubble sort : compilation error

I try to program some sorting, even though I don't have syntax or logic error in my code, while compiling I get an exception which seems to be related to the sorting method :

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at triBulle.bulle(triBulle.java:35)
at triBulle.main(triBulle.java:64)

Here's my code :

public static void bulle(int[] T)
{
    int n = T.length;
    boolean echange = true ;

    while((n>0) && (echange))
    {
        echange = false ;
        for(int j = 0 ; j<n ; j++)
        {
            if(T[j] >T[j+1])
            {
                int tmp = T[j];
                T[j] = T[j+1];
                T[j+1] = tmp;
                echange = true ;
            }
        }
        n = n-1;
    }

}

Thanks to check this out.

Upvotes: 0

Views: 86

Answers (1)

Tr&#233;s DuBiel
Tr&#233;s DuBiel

Reputation: 550

Someone correct me if I am wrong, but I am rather sure that, in java, an array with elements [0], [1], and [2] has a length of 3. So in your while-loop, if j is equal to length-1 then that is the last index. Therefore, when [j+1] gets called, you get an ArrayIndexOutOfBoundsException

One way to fix it would be

for(int j = 1 ; j<n ; j++)
    {
        if(T[j-1] >T[j])

Or

for(int j = 0 ; j<n-1 ; j++)
    {
        if(T[j] >T[j+1])

Upvotes: 1

Related Questions