Created
January 23, 2013 15:12
-
-
Save pdu/4607842 to your computer and use it in GitHub Desktop.
Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note:
You are not suppose to use the library's sort function for this problem. h…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| void sortColors(int A[], int n) { | |
| int pos0 = 0; | |
| int pos1 = n - 1; | |
| int pos2 = n - 1; | |
| while (pos0 < pos2) { | |
| if (A[pos0] == 0) | |
| pos0++; | |
| else if (A[pos0] == 1) { | |
| if (pos0 < pos1) { | |
| swap(A[pos0], A[pos1]); | |
| pos1--; | |
| } | |
| else | |
| pos0++; | |
| } | |
| else { | |
| swap(A[pos0], A[pos2]); | |
| pos2--; | |
| if (pos1 > pos2) | |
| pos1 = pos2; | |
| } | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment