Reputation: 55
I'm trying to use a bubble sort to alphabetize an array that I've read into a program. The code compiles without error but I get an Array Index Out Of Bounds Exception on my 'if' construct when I try to run the program. I have initialized int i to 0 to account for the first index of the array so I think my error is elsewhere. I'm not asking anyone to write code for me, just maybe a point in the right direction. Thanks for any help.
public static String[] bubbleSort(String[] inL)
{
String temp;
int i = 0, passNum;
for(passNum = 1; passNum <= (inL.length); i++) // controls passes through bubble sort
{
if(inL[i].compareToIgnoreCase(inL[i + 1]) < 0)
{
temp = inL[i];
inL[i] = inL[i + 1];
inL[i + 1] = temp;
}
}
return inL; // returns sorted array
} // end bubbleSort method
Upvotes: 0
Views: 552
Reputation: 7388
Your problem is the passNum <= (inL.length)
it should be passNum < (inL.length)
due to 0 being the first index of an array in java
Upvotes: 0
Reputation: 1679
Array.length
stores the total length of an array, starting counting at 1.
The first index in an array however is 0, meaning that the last index is length-1
.
adjust your check in your for-loop to fix the error
Upvotes: 0
Reputation: 234795
You never increment passNum
so i
continues incrementing forever. Also, array indexing in Java is based at 0. That means that the largest valid index is inL.length - 1
. Since the body of your loop accesses inL[i+1]
, you should arrange your code so that i
never exceeds inL.length - 2
. At a minimum, you should change <=
to <
in the for
loop termination test. (However, the logic of your comparison and incrementing escapes me; you need to fix that as well.)
Upvotes: 2
Reputation: 6230
You compare passNum
instead of i
against the length of the array. Since passNum
is never modified, the loop condition is always true, and i
gets incremented until it exceeds the range of the array.
Even if this particular issue is resolved, you may still run into problems with off-by-one errors with your current implementation. Consider whether you should compare i
against inL.length - 1
.
Upvotes: 2