I am trying to write a Recursive Bubble sort in Java and I’m getting an Index Out of Bounds Exception. What am I doing wrong and why am I getting this error?
Here is my code:
public static <T extends Comparable< ? super T>>
void sort(T [] a){
T tmp;
for(int i=0;i<a.length;i++){
if(a[i].compareTo(a[i+1])>0){
tmp = a[i];
a[i]=a[i+1];
a[i+1]=tmp;
sort(a);
}
System.out.println("i:"+i+" "+a[i]);
}
Also, even tho it sorts the array and I get the error at the end, it is printing all of the steps, how do I make it print the last final sorted array?
Is probably a simple answer but my brain is fried right now and can’t think straight.
Thanks in advance.
The loop should stop when
i < a.length-1, because in your code you access the positioni+1, and wheni == a.length - 1theni+1will be trying to access an element off the end of the array that doesn’t exist – hence, out of bounds.