forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PigeonHoleSorter.cs
61 lines (56 loc) · 1.63 KB
/
PigeonHoleSorter.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
57
58
59
60
61
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Sorting
{
/// <summary>
/// Only support IList<int> Sort
/// Also called CountSort (not CountingSort)
/// </summary>
public static class PigeonHoleSorter
{
public static void PigeonHoleSort(this IList<int> collection)
{
collection.PigeonHoleSortAscending();
}
public static void PigeonHoleSortAscending(this IList<int> collection)
{
int min = collection.Min();
int max = collection.Max();
int size = max - min + 1;
int[] holes = new int[size];
foreach (int x in collection)
{
holes[x - min]++;
}
int i = 0;
for (int count = 0; count < size; count++)
{
while (holes[count]-- > 0)
{
collection[i] = count + min;
i++;
}
}
}
public static void PigeonHoleSortDescending(this IList<int> collection)
{
int min = collection.Min();
int max = collection.Max();
int size = max - min + 1;
int[] holes = new int[size];
foreach (int x in collection)
{
holes[x - min]++;
}
int i = 0;
for (int count = size-1; count >= 0; count--)
{
while (holes[count]-- >0)
{
collection[i] = count + min;
i++;
}
}
}
}
}