- Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Copy pathCountingSorter.cs
56 lines (47 loc) · 1.37 KB
/
CountingSorter.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
usingSystem;
usingSystem.Collections.Generic;
usingAlgorithms.Common;
namespaceAlgorithms.Sorting
{
publicstaticclassCountingSorter
{
publicstaticvoidCountingSort(thisIList<int>collection)
{
if(collection==null||collection.Count==0)
return;
// Get the maximum number in array.
intmaxK=0;
intindex=0;
while(true)
{
if(index>=collection.Count)
break;
maxK=Math.Max(maxK,collection[index]+1);
index++;
}
// The array of keys, used to sort the original array.
int[]keys=newint[maxK];
keys.Populate(0);// populate it with zeros
// Assign the keys
for(inti=0;i<collection.Count;++i)
{
keys[collection[i]]+=1;
}
// Reset index.
index=0;
// Sort the elements
for(intj=0;j<keys.Length;++j)
{
varval=keys[j];
if(val>0)
{
while(val-->0)
{
collection[index]=j;
index++;
}
}
}
}
}
}