Sort color (flag of the Netherlands)

Source: Internet
Author: User

Algorithm idea:

The problem is a sorting problem, which can be divided into the front, middle, and rear parts of the array. Here's the idea: put the front and rear rows in front and back of the array, and the middle is naturally lined up. Set three pointers:begin,mid,end, and then traverse from the position of mid.

1. If the traversed position is 0, then it belongs to the front, swap mid and begin , then mid and begin to move forward.

2. If the traversed position is 1, it is in the middle, then only mid is moved.

3. If the traversed position is 2, then it belongs to the rear, and the mid and end are exchanged, since the swap mid The pointer is indeterminate, so only the end-- .

voidSortcolors (vector<int>&nums) {        intbegin=0, End=nums.size ()-1, mid=0;  while(mid<=end&&begin<=mid) {            if(nums[mid]==0) {swap (nums[mid],nums[begin]); Begin++; Mid++; }            Else if(nums[mid]==1) Mid++; Else if(nums[mid]==2) {swap (nums[mid],nums[end]); End--; }        }}

Sort color (flag of the Netherlands)

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: 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.