Asked by Derick

There is a bug in the sortArray method: one particular kind of input will cause a runtime error. In the box provided below, edit sortArray so that it behaves properly on these inputs.

public void sortArray () {
int beginP = 0;
int endP = myArray.length-1;
while(beginP<endP){
if((myArray[beginP]!=BLUE) && (myArray[endP]!=GREEN)){
swap(beginP, endP);
}
while((beginP < myArray.length) && (myArray[beginP]==BLUE)){
beginP++;
}
while(myArray[endP]==GREEN){
endP--;
}
}

Hint:
Look carefully at the nested while loop in the sortArray method body that increments the beginP variable. Now look at the corresponding loop that decrements the endP variable. How are the loop termination conditions different? Use this difference to guess at a string that will cause a runtime error.

Answers

Answered by TeacherJim
The hint gives the whole game away!

Compare:

while((beginP < myArray.length) && (myArray[beginP]==BLUE))

with

while(myArray[endP]==GREEN){

What happens if GREEN is at the end of the array?
Answered by Javs
while(myArray[endP]==GREEN){

needs to be if rather than while.
Answered by Anonymous
int beginP = 0;
int endP = myArray.length-1;
while(beginP<endP){
if((myArray[beginP]!=BLUE) && (myArray[endP]!=GREEN)){
swap(beginP, endP);
}
while((beginP < myArray.length) && (myArray[beginP]==BLUE)){
beginP++;
}
while(myArray[endP]==GREEN){
endP-- = "";
}
}
There are no AI answers yet. The ability to request AI answers is coming soon!