Sort Colors, sortcolors
This article is in the study of the summary, welcome to reprint but please note the Source: http://blog.csdn.net/pistolove/article/details/43302343
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.
Ideas:
(1) The question is to give an array containing three colors: red, white, and blue (the order is disordered), and adjust it to the red-> White-> blue order. Where, 0, 1, and 2 correspond to red, white, and blue respectively.
(2) The essence of this question is a sorting operation. However, there are many identical elements, which need to be determined. The method used in this article is relatively simple. First, traverse the array to determine the number of 0, 1, and 2. Then traverse the array and fill in 0, 1 and 2 in the array in sequence. The specific operation is as long as the number of 0 is greater than zero, fill 0 in the array, and then the number is reduced by 1 until 0 is all placed in the array, add the numbers 1 and 2 to the array. Finally, the obtained array is distributed in the sequential order of 0 --> 1 --> 2.
(3) I hope this article will help you.
The algorithm code is implemented as follows:
/** * * @author liqq */public void sortColors(int[] A) {if (A == null || A.length <= 1)return;int _zeor = 0;int _one = 0;int _two = 0;for (int i = 0; i < A.length; i++) {if (A[i] == 0)_zeor++;if (A[i] == 1)_one++;if (A[i] == 2)_two++;}for (int i = 0; i < A.length; i++) {if (_zeor > 0) {A[i] = 0;_zeor--;continue;}if (_one > 0) {A[i] = 1;_one--;continue;}if (_two > 0) {A[i] = 2;_two--;}}}