Three-Color Sorting of impaired glucose

Source: Internet
Author: User

The given string contains only three characters: "R" "G" "B". Sort the string. The final result is that R is placed after B in the previous G.
Requirement: the space complexity is O (1), and only one string can be traversed.
Http://write.blog.csdn.net/postedit in July Daniel's blog section 8 has the answer to this question.

When I was doing the question, I felt that if I had to sort two characters, it would be a trip in the fast sorting, and the two pointers would have been done. However, I also thought that three pointers would have to be used, but I don't know how to move it. I suddenly realized it was easy to read July's blog. The specific ideas are as follows:

The first begin, the first current in, and the second end are exchanged.

1. Current traversal. The entire array sequence. Current indicates 1 does not move,
2. Current refers to R, which is exchanged with begin, and then current ++, begin ++,
3. "current" refers to "B", which is switched with "end". Then, "current" does not move, and "end" is used --.

The three pointers control the positions of three RGB colors respectively, starting to point begin current to the first and end to the last

While (current <= end)
{
If (array [current] = 'R ')
{
Swap (array [current], array [begin]);
Current ++;
Begin ++;
}
Else if (array [current] = 'G ')
{
Current ++;
}

Else // when array [current] = 'B'
{
Swap (array [current], array [end]);
End --;
}
}

We also see how to deal with expansion, such as four-color, four-character

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.