Leetcode: Sort colors count sorting

Source: Internet
Author: User

Sort colors:

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.

 

Problem Analysis:

When we know the value range of the elements to be sorted, we can use the T (n) = O (n) sorting method.

In this question, it is clear that the value range of the elements to be sorted is known, and other elements such as sorting student scores and sorting employee ages can be sorted by count.

The basic idea of counting sorting is to determine the number of elements smaller than X for each input element x. Then place X in the position of the final output array.

Class solution {public: void sortcolors (int A [], int N) {assert (! = NULL & n> = 0); Auto result = minmax_element (A, A + n); int minval = * result. first; int maxval = * result. second; int totalcount = maxval-minval + 1; if (totalcount = 1) return; int * COUNT = new int [totalcount] (); For (INT I = 0; I <n; ++ I) {++ (count [A [I]-minval]) ;}for (INT I = 1; I <totalcount; ++ I) {count [I] + = count [I-1];} int * TMP = new int [N] (); For (INT I = n-1; I> = 0; -- I) {// It must start from the back, otherwise it is not a stable algorithm TMP [count [A [I]-minval]-1] = A [I]; -- (count [A [I]-minval]);} copy (TMP, TMP + n, a); Delete [] count; Delete [] TMP ;}};

 

Animation demo: http://www.cs.usfca.edu /~ Galles/visualization/countingsort.html

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.