A rope hang red three colors of white and blue flag, and arranged out of order, the program is used to classify three flags in the same color, order blue-white-red, can only exchange 2 flags at a time, with a minimum of steps to complete.
Algorithm Description: Simply swap the red and blue flags, the flag and the flag are in place, and the white flag is naturally in place.
1) If the white flag is in the position of the element is a white flag, indicating that the position of the element should be here, will white++, and then process the next flag;
2) If the element in White's position is a blue flag, it means that the blue flag and the element where the blue variable is located should be swapped, and then blue++, white++, to handle the next flag;
3) If the element at White's location is a red flag, it means that the red flag is swapped with the elements of the red variable, and then the red--, continues to process the next flag.
1 namespacesection10_threeflags{2 intcount;3 Charcolor[]="RWBWWBRBWR";4 intblue,white,red;5 //Exchange variable A and B6 voidSwapCharAChar*b) {7 Chartemp;8 inti;9temp = *A;Ten*a=*b; One*b=temp; Acount++; -printf"The %dth order exchanged\n", count); - for(i=0;i< (int) strlen (color); i++){ theprintf"%c", Color[i]); - } -printf"\ n"); - } + voidthreeflags () { - while(color[white]=='b'){ +blue++; Awhite++; at } - while(color[red]=='R'){ -red--; - } - while(white<=Red) { - if(color[white]=='R'){ inSwap (&color[white],&color[red]); -red--; to while(color[red]=='R'){ +red--; - } the } * while(color[white]=='W'){ $white++;Panax Notoginseng } - if(color[white]=='b'){ theSwap (&color[white],&Color[blue]); +blue++; Awhite++; the } + } - } $ voidrunthreeflags () { $ intI,len; -Blue=white=0; -len=strlen (color); thered=len-1; -Count=0;Wuyiprintf"The original flags ' array is as follows:\n"); the for(i=0; i<len;i++){ -printf"%c", Color[i]); Wu } -printf"\ n"); About threeflags (); $printf"The last result: \ n"); - for(i=0; i<len;i++){ -printf"%c", Color[i]); - } Aprintf"\ n"); +}
Algorithm analysis of three-color flag algorithm