The random access feature of the array is used for counting sorting. The number k to be sorted is converted into the subscript K of the array, the value of a [k] with K as the underlying value in this array represents the number of K. This sorting is very fast, but the application conditions are harsh.
It is mainly affected by the sequence scale (N) and the sequence maximum value (max (N) to be sorted. If max (n) is too large, the algorithm space complexity is relatively high, it is also a constraint of this algorithm. The following two methods are implemented:
1) the first method is faster than the 2nd method, but it is not stable and cannot be used for base counting sorting.
Private void countsort (INT [])
{
List <int> theC = new list <int> ();
Int thelen = A. length;
Int themaxval = 0;
For (INT I = 0; I <thelen; I ++)
{
If (A [I]> themaxval)
{
Themaxval = A [I];
Addlength (theC, themaxval );
}
TheC [A [I]-1] ++;
Thecount ++;
}
Int J = 0;
For (INT I = 0; I <themaxval; I ++)
{
For (int K = 0; k <theC [I]-1; k ++)
{
A [J] = I + 1;
J ++;
}
}
}
2) the textbook algorithm has the advantage of stability and can be used to sort the base count. The speed is slower than the previous one. The time is about 2 (n + k)
Private int [] countsort2 (INT [])
{
// Use the list to dynamically increase the length.
List <int> theC = new list <int> ();
Int thelen = A. length;
Int [] theb = new int [thelen];
Int themaxval = 0;
For (INT I = 0; I <thelen; I ++)
{
If (A [I]> themaxval)
{
Themaxval = A [I];
Addlength (theC, themaxval );
}
TheC [A [I]-1] ++;
Thecount ++;
}
For (INT I = 1; I <themaxval; I ++)
{
TheC [I] + = theC [I-1];
Thecount ++;
}
For (INT I = theLen-1; I> = 0; I --)
{
Theb [theC [A [I]-1]-1] = A [I];
(TheC [A [I]-1]) --;
Thecount ++;
}
Return theb;
}
Private void addlength (list <int> C, int maxlen)
{
Int ilen = maxlen-C. count;
For (INT I = 0; I <ilen; I ++)
{
C. Add (0 );
Thecount ++;
}
}
Postscript: The counting algorithm is suitable for the case where the sequence elements are concentrated and the difference value is small. If you know the maximum and minimum values of a sequence, and the difference between the maximum and minimum values is not very large, this sort is more suitable.
Sort letters, and sort simple numbers (0-9.