Reputation: 2329
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.
Upvotes: 3
Views: 4300
Reputation: 1
The IndexOutOfBoundsException
happens because your loop tries to access a[i+1]
when i
is at the last index (a.length - 1)
, which goes out of bounds.
To fix it, adjust the loop to run until i < a.length - 1
, so a[i+1]
is always valid:
public static <T extends Comparable<? super T>> void sort(T[] a) {
T tmp;
boolean swapped = false;
for (int i = 0; i < a.length - 1; i++) {
if (a[i].compareTo(a[i + 1]) > 0) {
tmp = a[i];
a[i] = a[i + 1];
a[i + 1] = tmp;
swapped = true;
}
}
if (swapped) {
sort(a);
} else {
// Print the final sorted array
for (T element : a) {
System.out.print(element + " ");
}
System.out.println();
}
The error happened because the loop tried to access an index that doesn’t exist (a[i+1]
when i
is at a.length - 1)
. The fix ensures valid index access and lets the array sort correctly, printing the final sorted array only once at the end.
Upvotes: 0
Reputation: 92
Try this.
public static void bubbleSort(Object[] source, int fromIndex, int endIndex){
if(fromIndex==endIndex){
return;
}
else{
if(((Comparable) source[fromIndex]).compareTo(source [fromIndex+1])>0){
Object temp=source[fromIndex];
source[fromIndex]=source[fromIndex+1];
source[fromIndex+1]=temp;
}
bubbleSort(source,fromIndex+1,endIndex);
}
bubbleSort(source,fromIndex,endIndex-1);
}
Upvotes: -1
Reputation: 236004
The loop should stop when i < a.length-1
, because in your code you access the position i+1
, and when i == a.length - 1
then i+1
will be trying to access an element off the end of the array that doesn't exist - hence, out of bounds.
Upvotes: 10
Reputation: 234795
You've written your loop so that i
gets as bit as a.length - 1
. Then you are trying to access a[i+1]
, which is an out-of-bounds index when i == a.length - 1
. Lower your loop's limit by 1.
Upvotes: 5