Question of the Dutch flag

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.