# 题目描述

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.

# 题目解答

#### 解题思路

• 先统计red , white, blue 三组颜色的个数，然后分别按照颜色的个数建立数组
• 双指针法

#### 代码实现

• 计数排序
public class Solution {
public void sortColors(int[] nums) {
if(nums == null || nums.length == 0)
return ;
int redCount = 0, whiteCount = 0, blueCount = 0;
for(int i = 0; i < nums.length; i++){
switch(nums[i]){
//红色
case 0:
redCount++;
break;
case 1:
whiteCount++;
break;
case 2:
blueCount++;
break;
default:
}
}
for(int i = 0; i < nums.length; i++){
if(redCount > 0){
nums[i] = 0;
redCount--;
}else if(whiteCount > 0){
nums[i] = 1;
whiteCount--;
}else {
nums[i] = 2;
}
}
}
}

public class Solution {
/**
*双指针 一个redPos, 一个bluePos
*/
public void sortColors(int[] nums) {
if(nums == null || nums.length == 0)
return ;

int redPos = 0, bluePos = nums.length-1;
int i = 0;
while(i <= bluePos){
if(nums[i] == 0){
//0交换回来的只能是1 所以直接加
swap(nums, redPos, i);
redPos++;
}else if(nums[i] == 2){
//2交换回来的可能是0 所以要继续判断
swap(nums, bluePos, i);
bluePos--;
continue;
}

i++;
}
}

public void swap(int[] nums, int i, int j){
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}

• 本文已收录于以下专栏：

tt

## Internal Sorting Algorithms Part 2/2: Advanced Sorts

Internal Sorting Algorithms Part 2/2: Advanced Sorts目录 Internal Sorting Algorithms Part 22 Advanced ...

## UVA - 110 Meta-Loopless Sorts（元排序 回溯）

Meta-Loopless Sorts  Background  Sorting holds an important place in computer scienc...

## Princeton Algorithms: Part 2 [week 3: Radix Sorts]

Exercise Question 1 (seed = 215242)Suppose that you run LSD radix sort on the following ...

## Internal Sorting Algorithms Part 1/2: Elementary Sorts

Internal Sorting Algorithms Part 1/2: Elementary Sorts目录 Internal Sorting Algorithms Part 12 Element...

## Algorithms - Week 2-1 Elementary Sorts

Selection Sort, Insertion Sort, Shell Sort, Shuffling, Convex Hull.

## 排序算法之Bubble sorts and variants

0. 前言 Simple Sorts包括两种排序算法： 选择排序(Selection sort) 和 插入排序（Insertion sort)。 代码基于C++11编写，编译器使用g++4.9.2 版...

## uva 110 Meta-Loopless Sorts 用程序写程序 有点复杂的回溯水题

• hcbbt
• 2013年07月23日 11:31
• 1035

## 排序算法之Efficient sorts

0. 前言 Efficient sorts包括两种排序算法： 归并排序(Merge sort) 、 堆排序（Heap sort) 、快速排序(Quick sort)。 代码基于C++11编写，编译器使...

举报原因： 您举报文章：Sorts Colors 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)