-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
CountingSorter.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
using System;
using System.Collections.Generic;
using Algorithms.Common;
namespace Algorithms.Sorting
{
public static class CountingSorter
{
public static void CountingSort(this IList<int> collection)
{
if (collection == null || collection.Count == 0)
return;
// Get the maximum number in array.
int maxK = 0;
int index = 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 = new int[maxK];
keys.Populate(0); // populate it with zeros
// Assign the keys
for (int i = 0; i < collection.Count; ++i)
{
keys[collection[i]] += 1;
}
// Reset index.
index = 0;
// Sort the elements
for (int j = 0; j < keys.Length; ++j)
{
var val = keys[j];
if (val > 0)
{
while (val-- > 0)
{
collection[index] = j;
index++;
}
}
}
}
}
}