對於紅綠藍三種小球這個問題,相似快排中 partition 過程。不過,要用三個指針,一前 begin,一中 current,一後 end,倆倆交換。優化
while(current<=end){spa
一、 current 指 1 ,current++,
指針
二、 current 指 0,與 begin 交換,然後 current++, begin++,code
三、 current 指 2,與 end 交換,然後, current 不動, end--。it
}io
具體代碼:
ast
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; }
優化寫法(其實也不優化,可是可以減小交換次數):class
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; }