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.
We make two passes
First pass put all the reds together by exchanging contiguous positions with red only
Second pass with all whites together
The rest automatically follow.
Void sortColors ( ref list <int> colors )
{
For ( int color = 0; color < 2; color ++;)
For (Int src = 0; src < colors.count (); src++)
{
If ( color > 0 && colors [src] <= color) continue;
Int d = src +1;
If (colors [src] != color){
While ( d < colors.count () && colors [d] != color) d++;
If ( d != colors.count()) swap colors [src], colors [d]
}
}
We make two passes
First pass put all the reds together by exchanging contiguous positions with red only
Second pass with all whites together
The rest automatically follow.
Void sortColors ( ref list <int> colors )
{
For ( int color = 0; color < 2; color ++;)
For (Int src = 0; src < colors.count (); src++)
{
If ( color > 0 && colors [src] <= color) continue;
Int d = src +1;
If (colors [src] != color){
While ( d < colors.count () && colors [d] != color) d++;
If ( d != colors.count()) swap colors [src], colors [d]
}
}
No comments:
Post a Comment