Sort Colors, sortcolors

Source: Internet
Author: User

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--;}}}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.