void sortColors(int A[], int n) {
int beg = 0, end = n-1;
for(int i = 0; i < n; i++)
{
if(A[i] == 0)
{
while(beg < i && A[beg] == 0)
{
beg++;
}
if(beg < i)
{
int tmp = A[beg];
A[beg] = A[i];
beg++;
A[i] = tmp;
i--;
}
}
else if(A[i] == 2)
{
while(end > i && A[end] == 2)
{
end--;
}
if(end > i)
{
int tmp = A[end];
A[end] = A[i];
end--;
A[i] = tmp;
i--;
}
}
}
}
基本思想是:遇到0,尽量往左排;遇到2,尽量往右排