The. Sort Colors

Source: Internet
Author: User

Given an array with n objects colored red, white or blue, sort them so, objects of the same color is Adjacen T, with the colors in the order red, white and blue.

Here, we'll use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.

Note:
You aren't suppose to use the library's sort function for this problem

==========

There are three colors of objects, the colors are red,waite,blue, respectively, using an array of 0,1,2 to represent.

The requirements are: sort the objects by color red,waite,blue.

=======

Ideas:

The idea of using a quick sort:

Begin: Point to the location that will be sorted to red (0)

End: Point to where you want to sort blue (2)

Curr: Traverse Pointer,

If the current element is 0, then and begin position swap, notify begin++,curr++

If the current element is 1,curr++

If the current element is 2, then the end position is swap, but the curr element cannot be incremented, end--

====

Code

classSolution { Public:    voidSortcolors (vector<int>&nums) {        intn =nums.size (); intCurr,begin,end; Curr= BEGIN =0; End= N1;  while(curr<=end) {            if(nums[curr]==0) {Swap (Nums[begin++],nums[curr++]); }Else if(nums[curr]==1) {Curr++; }Else if(nums[curr]==2) {swap (Nums[end],nums[curr]); End--; }        }    }};

The. Sort Colors

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.