How would I alter my code?
If my code:
Code Java:
public void sortArray () {
int beginP = 0;
int endP = myArray.length-1;
while(beginP<endP){
if((myArray[beginP]!=GREEN) && (myArray[endP]!=BLUE)){
swap(beginP, endP);
}
while((beginP < myArray.length) && (myArray[beginP]==GREEN)){
beginP++;
}
while(myArray[endP]==BLUE){
endP--;
}
}
produced: G G G B B B B
how would I alter it so that it would produce: B B B B G G G?
I feel as though I am missing one step, but I cannot put my finger on it.
Re: How would I alter my code?
Alter it how? Why can't you just use the same sorting algorithm and change every BLUE with a GREEN and vice versa?
Re: How would I alter my code?
I tried that before, I don't know why that didn't work.
Re: How would I alter my code?
Have you tried debugging the code by adding some println()s to show what is happening?
Re: How would I alter my code?
I would recommend implementing a compareTo() method that determines which color comes before which.
Something like:
Code Java:
/**
* Blue comes before green.
*
* Returns less than 0 if item1 comes before item2
* Returns 0 if item1 comes at the same place as item2
* Returns greater than 0 if item1 comes after item2
*/
public static int compareTo(ColorItem item1, ColorItem item2)
{
int val1 = 0;
int val2 = 0;
if(item1 == BLUE)
{
val1 = 1;
}
else
{
val1 = 2;
}
if(item2 == BLUE)
{
val2 = 1;
}
else
{
val2 = 2;
}
return val1 - val2;
}
Then, somewhere in your code implement a standard sorting algorithm (say, selection sort because it's very easy).