Question of the flag of the Netherlands:
Existing red, white, blue three different colors of the ball, disorderly order together, rearrange these small balls, so that the red and white blue three colors with the ball together.
Problem Analysis:
The problem is converted to: given array a[0,1,..., N-1], the element can only take 0,1,2 three values, the design algorithm makes the array rearranged into "000...111..222" form.
You can use three cursors, begin=0,cur=0,end=n-1.
Program implementation:
1 /***************************************2 FileName HollandFlag.cpp3 Author:godfrey4 CREATEDTIME:2016/5/45 ****************************************/6#include <iostream>7#include <cstring>8#include <vector>9#include <algorithm>Ten#include <stdio.h> One#include <stdlib.h> A - using namespacestd; - the voidHollandflag (intAintsize) { - intBegin =0; - intend = Size-1; - intCur =0; + while(cur <=end) { - if(A[cur] = =2){ + swap (a[cur],a[end]); AEnd--; at } - Else if(A[cur] = =1){ -Cur + +; - } - Else if(A[cur] = =0){ -Swap (A[cur],a[begin]);//This simplifies the steps to remind you whether the cur and begin are the same, taking into account the situation inBegin + +; -Cur + +; to } + } - } the intMain () * { $ intA[] = {0,1,2,0,0,2,1,2,1,2,2,1,1,0};Panax Notoginseng intSize =sizeof(a)/sizeof(int); - for(intI=0; i<size;i++){ thecout<<a[i]<<" "; + } Acout<<Endl; the Hollandflag (a,size); +cout<<"-----------after adjusting------------"<<Endl; - for(intI=0; i<size;i++){ $cout<<a[i]<<" "; $ } -cout<<Endl; - return 0; the}
Operation Result:
Reprint please specify the source:
C + + Blog Park: godfrey_88
http://www.cnblogs.com/gaobaoru-articles/
Question of the Dutch flag