There is an array, the length of N, which is only 0, 1, 2 (respectively for red, white, blue), now requires the way through 22 exchanges, so that 0 in the front, 1 in the middle, 2 in the last.
The code implementation is as follows:
Package com.threeTop.www;
/**
* Dutch flag issue
* @author WJGS * */Public
class Dutchflag {
/**
* Dutch flag issue
* @param array< c9/>*/public
static void sort (int []array)
{
int begin=0;
int end=array.length-1;
int current=0;
while (Current<=end)
{
if (array[current]==0)
{
swap (array,current,begin);
begin++;
current++;
}
else if (array[current]==1)
{
current++
} else if (array[current]==2)
{
swap (array,current,end);
end--
}
}
System.out.print ("sorted result:");
for (int i=0;i<array.length;i++)
{
System.out.print (array[i]+ ",");
}
}
Swap two elements
private static void Swap (int[] array, int x, int y)
{
int temp=array[x];
Array[x]=array[y];
array[y]=temp;
}
public static void Main (string[] args)
{
int []array={1,1,0,0,2,2,1,0,1,2,1,0,2};
int []array2={1,1,0,0,2,2,1,0,1,2,1,0,2};
Dutchflag.sort (array);
System.out.println ();
Dutchflag.sort (array2);
}