# eaglet

::  ::  ::  ::  ::

Counting sort (sometimes referred to as ultra sort or math sort[1]) is a sorting algorithm which (like bucket sort) takes advantage of knowing the range of the numbers in the array to be sorted (array A). It uses this range to create an array C of this length. Each index i in array C is then used to count how many elements in A have the value i; then counts stored in C can then be used to put the elements in A into their right position in the resulting sorted array. The algorithm was created by Harold H. Seward in 1954.

Counting sort
Depends on a key assumption: numbers to be sorted are integers in{0, 1, . . . , k}.
Input: A[1 . . n], where A[ j ] ∈ {0, 1, . . . , k} for j = 1, 2, . . . , n. Array A and
values n and k are given as parameters.
Output: B[1 . . n], sorted. B is assumed to be already allocated and is given as a
parameter.
Auxiliary storage: C[0 . . k]
8-4 Lecture Notes for Chapter 8: Sorting in Linear Time
COUNTING-SORT(A, B, n, k)
for i ← 0 to k
do C[i ] ← 0
for j ← 1 to n
do C[A[ j ]] ← C[A[ j ]] + 1
for i ← 1 to k
do C[i ] ← C[i ] + C[i − 1]
for j ← n downto 1
do B[C[A[ j ]]] ← A[ j ]
C[A[ j ]] ← C[A[ j ]] − 1
Do an example for A = 21, 51, 31, 01, 22, 32, 02, 33
Counting sort is stable (keys with same value appear in same order in output as
they did in input) because of how the last loop works.

# 方案1

public static void Sort(int[] A, out int[] B, int k)
{
Debug.Assert(k > 0);
Debug.Assert(A != null);

int[] C = new int[k + 1];
B = new int[A.Length];

for (int j = 0; j < A.Length; j++)
{
C[A[j]]++;
}

for (int i = 1; i <= k; i++)
{
C[i] += C[i-1];
}

for (int j = A.Length - 1; j >= 0; j--)
{
B[C[A[j]]-1] = A[j];
C[A[j]]--;
}

}

# 方案2

public static void Sort(int[] A, int k)
{
Debug.Assert(k > 0);
Debug.Assert(A != null);

int[] C = new int[k + 1];

for (int j = 0; j < A.Length; j++)
{
C[A[j]]++;
}

int z = 0;

for (int i = 0; i <= k; i++)
{
while (C[i]-- > 0)
{
A[z++] = i;
}
}
}

# 和快速排序的速度比较

int[] A = new int[1000000];
int[] B = new int[1000000];

Random rand = new Random();

for (int i = 0; i < A.Length; i++)
{
A[i] = rand.Next(0, 100);
}

A.CopyTo(B, 0);

Stopwatch sw = new Stopwatch();
sw.Start();
Array.Sort(B);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

sw.Reset();
sw.Start();

CountingSort.Sort(A, 100);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

134 //快速排序
18   //计数排序