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.
思路:这题要实现的是将所有的0放到数组的左边,将所有的2放到数组的右边,采取快速排序的思想,将2都交换到数组的后面,将0都交换到数组的前面,具体代码如下:
public void sortColors(int[] nums) {
if (nums.length==0||nums.length==1) return;
int end=nums.length-1;
int beign=0;
for (int i = 0; i <=end; i++) {
while (nums[i]==2&i<end) {
int temp=nums[i];
nums[i]=nums[end];
nums[end--]=temp;
}
while (nums[i]==0&&i>beign){
int temp=nums[i];
nums[i]=nums[beign];
nums[beign++]=temp;
}
}
}