I'm in an intro to Java course and am just trying to get ahead of the curve with some practice, so I'm making a bubble sort program. For some reason, it only will run through the outer loop twice.
public ArrayList SortArray(ArrayList<Integer> u) {
int temp;
int spot;
for (int isOrdered = 1; isOrdered == 1;) {
for (spot = 0; spot < u.size() - 1; spot ++) {
System.out.println(u.get(spot) + " " + u.get(spot + 1) + " " + spot);
if (u.get(spot) > u.get(spot + 1)) {
temp = u.get(spot + 1);
u.set(spot + 1, u.get(spot));
u.set(spot, temp);
isOrdered = 1;
}
else {
isOrdered = 0;
}
}
}
return u;
}
As far as I can tell, what's happening is after the second iteration, it doesn't reset 'spot' to 0 so it doesn't run through the loop again. Any ideas?
Well, for starters that's an ... unusual way of using a for loop to implement a while loop. Try using a boolean for isOrdered
and a while(!isOrdered)
for a statement like that.
As Ted Hopp's comment said, your logic isn't quite right. What your code is doing is that it will sort ONE value in the list and once that value has "bubbled up" your flag is set to true.
You need your outer loop's condition to be that it keeps running until ALL cells are in order.
Right now your flag simply says it's sorted, when you've gone through the list, but what it needs to do is be true when it's gone through the list without performing a swap.
Try to implement that without looking, then if you can't get it (I'm assuming you're interested in doing it yourself since you're working ahead in your class) take a look at the sample here.