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.

public class Solution {
//Given: 2, 0, 2, 1, 1
// i = 0: 1, 0, 2, 1, 2 (swap 2 and 1)
// i = 1: 0, 1, 2, 1, 2
// i = 2: 0, 1, 2, 1, 2
// 0, 1, 1, 2, 2
public void sortColors(int[] nums) {
//left&right are the two ends of the subarray that we're dealing with
int left = 0;
int right = nums.length - 1;
//gradually shrink the array by subtracting right by 1 each time
for (int i = 0; i <= right; i++) {
while(nums[i] == 2 && i < right){
//swap 2 and nums[right]
int temp = nums[i];
nums[i] = nums[right];
nums[right--] = temp;
}
while(nums[i] == 0 && i > left) {
//swap 0 and nums[i]
int temp = nums[i];
nums[i] = nums[left];
nums[left++] = temp;
}
}
return;
}
}

### Like this:

Like Loading...

*Related*