Created
May 9, 2013 19:35
-
-
Save daifu/5549965 to your computer and use it in GitHub Desktop.
Sort Colors
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
/* | |
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. | |
Algorithm: | |
1. There are 3 separators, red, white, and blue | |
2. Since the increate interator and put the correct int into | |
a correct bucket by swaping them execept the white color. | |
*/ | |
public class Solution { | |
public void sortColors(int[] A) { | |
// Start typing your Java solution below | |
// DO NOT write main() function | |
int red = 0; | |
int white = 0; | |
int blue = A.length-1; | |
while(blue >= white) { | |
if(A[white] == 1) { | |
white++; | |
} else if(A[white] == 0) { | |
swap(A, white, red); | |
red++; | |
white++; | |
} else if(A[white] == 2) { | |
swap(A, white, blue); | |
blue--; | |
} | |
} | |
return; | |
} | |
public void swap(int[] A, int i, int j) { | |
int tmp = A[i]; | |
A[i] = A[j]; | |
A[j] = tmp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment