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