java - Bubble sort : compilation error -


i try program sorting, though don't have syntax or logic error in code, while compiling exception seems related sorting method :

exception in thread "main" java.lang.arrayindexoutofboundsexception: 5 @ tribulle.bulle(tribulle.java:35) @ tribulle.main(tribulle.java:64) 

here's 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 check out.

someone correct me if wrong, rather sure that, in java, array elements [0], [1], , [2] has length of 3. in while-loop, if j equal length-1 last index. therefore, when [j+1] gets called, arrayindexoutofboundsexception

one way fix 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]) 

Comments