三色旗問題又叫荷蘭旗問題,前提是有一個無序的char數組,裏面的元素只能是{‘R’,'G','B'}中的一個,比如{'B','R','G','R','B','B','G','B','R'},現在要求不允許藉助額外的空間,即只能通過自身元素交換的方法將數組重排序,最終達到RGB順序排序,比如例子中的數組排序後變爲:RRRGGBBBB。
算法分析:
分別定義三個指針,rindex, gindex, bindex, rindex和gindex初始時指向第一個元素,gindex指向最後一個。
rindex始終指向左邊第一個非R的元素,它的作用就是當gindex爲R時和gindex的元素進行交換。
gindex用來遍歷數組,當gindex<=bindex時遍歷結束。
bindex從右邊遞減始終指向從右邊數第一個非B的元素。
當gindex指向的元素是R時,和rindex的元素進行交換,gindex++, rindex++;
當gindex指向的元素是G時,什麼都不做,gindex++;
當gindex指向的元素是B時,和bindex指向的元素互換,bindex--;(這一步爲什麼gindex++,原因請思考這樣的數組GBRB)
當遍歷完數組之後所有的R都在左邊,G在中間,B在右邊
java實現代碼如下:
package com.jackie.algorithm;
public class SortThreeColors {
//Swap the specified indexs of a char array
private static void swap(char[] colors,int a, int b){
char tmp ;
tmp = colors[a];
colors[a] = colors[b];
colors[b] = tmp;
}
//Sort the char arrays by "RGB" order
public static char[] sortThreeColors(char[] colors){
int rindex = 0;
int gindex = 0;
int bindex = colors.length-1;
while(gindex < bindex){
if(colors[gindex] == 'R'){
if(rindex != gindex ){
swap(colors, rindex, gindex);
}
rindex++;
gindex++;
}else if (colors[gindex] == 'B'){
if(bindex != gindex){
swap(colors, gindex, bindex);
}
bindex--;
}else{
gindex++;
}
}
return colors;
}
public static void main(String[] args) {
char colors[] = new char[]{'B','R','G','R','B','B','G','B','R'};
colors = sortThreeColors(colors);
System.out.println(colors);
}
}