对于红绿蓝三种小球这个问题,类似快排中 partition 过程。不过,要用三个指针,一前 begin,一中 current,一后 end,俩俩交换。
while(current<=end){
1、 current 指 1 ,current++,
2、 current 指 0,与 begin 交换,而后 current++, begin++,
3、 current 指 2,与 end 交换,而后, current 不动, end--。
}
具体代码:
inline void swap(int &a,int &b){
int tmp=a;
int a=b;
int b=tmp;
}
void Sort_RGB(int a[],int start,int last){
if(start>=last) return;
int begin=start;
int current=start;
int end=last;
while( current<=end )
{
if( array[current] ==0 )
{
swap(array[current],array[begin]);
++current;
++begin;
}
else if( array[current] == 1 )
{
++current;
}
else //When array[current] =2
{
swap(array[current],array[end]);
--end;
}
}
//最终begin指向第一个绿球,current指向第一个蓝求
return;
}
优化写法(其实也不优化,但是能够减少交换次数):
inline void swap(int &a,int &b){
int tmp=a;
int a=b;
int b=tmp;
}
void Sort_RGB(int a[],int start,int last){
if(start>=last) return;
int begin=start;
int current=start;
int end=last;
while( current<=end )
{
if( array[current] ==0 )
{
swap(array[current],array[begin]);
while(array[++current]==1){};//找到非绿球
begin++;
}
else if( array[current] == 1 )
{
while(array[++current]==1){};//找到非绿球为止
}
else //When array[current] =2
{
swap(array[current],array[end]);
while(array[--end]==2){};//找到非蓝球为止
}
}
//最终begin指向第一个绿球,current指向第一个蓝求
return;
}