题目:
荷兰国旗问题。要求重新排列一个由字符R,W,B(R代表红色,W代表白色,B代表兰色,这都是荷兰国旗的颜色)构成的数组,使得所有的R都排在最前面,W排在其次B排在最后。为荷兰国旗问题设计一个算法,其时间性能是O(m)
代码:
#include <iostream>using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */const int N = 20;void swap_ab (int *p, int *q){int temp = *p;*p = *p;*q = temp;}void process (int a[], int n) {int *p, *q;p = q = a;while(p != a + n - 1){if (*(p+1) < * p){q = p + 1;while(*q < *(q-1)){swap_ab(q, q-1);--q;}}++p; }}int main(int argc, char** argv) {int a[N] = {0, 2, 1, 2, 0, 1, 0, 2, 2, 1, 0, 1, 2, 1, 1, 0, 0, 1, 1, 2};cout << "处理后的数组序列为: " << endl;process(a, N);for (int i = 0; i < N; i++) {cout << a[i] << " "; }cout << endl;return 0;}
Java解法见及详细荷兰国旗算法问题解法见:/p/356604b8903f