Skip to content

Commit 96ee270

Browse files
author
Lucas Lemaire
committed
Add PigeonHole sort algorithm with test
1 parent 81f9a0c commit 96ee270

File tree

2 files changed

+93
-0
lines changed

2 files changed

+93
-0
lines changed
+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using System.Collections.Generic;
2+
using System.Linq;
3+
4+
namespace Algorithms.Sorting
5+
{
6+
/// <summary>
7+
/// Only support IList<int> Sort
8+
/// Also called CountSort (not CountingSort)
9+
/// </summary>
10+
public static class PigeonHoleSorter
11+
{
12+
public static void PigeonHoleSort(this IList<int> collection)
13+
{
14+
collection.PigeonHoleSortAscending();
15+
}
16+
17+
public static void PigeonHoleSortAscending(this IList<int> collection)
18+
{
19+
int min = collection.Min();
20+
int max = collection.Max();
21+
int size = max - min + 1;
22+
int[] holes = new int[size];
23+
foreach (int x in collection)
24+
{
25+
holes[x - min]++;
26+
}
27+
28+
int i = 0;
29+
for (int count = 0; count < size; count++)
30+
{
31+
while (holes[count]-- > 0)
32+
{
33+
collection[i] = count + min;
34+
i++;
35+
}
36+
}
37+
}
38+
39+
public static void PigeonHoleSortDescending(this IList<int> collection)
40+
{
41+
int min = collection.Min();
42+
int max = collection.Max();
43+
int size = max - min + 1;
44+
int[] holes = new int[size];
45+
foreach (int x in collection)
46+
{
47+
holes[x - min]++;
48+
}
49+
50+
int i = 0;
51+
for (int count = size-1; count >= 0; count--)
52+
{
53+
while (holes[count]-- >0)
54+
{
55+
collection[i] = count + min;
56+
i++;
57+
}
58+
}
59+
}
60+
}
61+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
using System.Collections.Generic;
2+
using System.Diagnostics;
3+
using System.Linq;
4+
using Algorithms.Sorting;
5+
6+
namespace C_Sharp_Algorithms.AlgorithmsTests
7+
{
8+
public static class PigeonHoleSortTest
9+
{
10+
public static void DoTest()
11+
{
12+
DoTestAscending();
13+
DoTestDescending();
14+
}
15+
16+
public static void DoTestAscending()
17+
{
18+
List<int> numbers = new List<int> { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };
19+
numbers.PigeonHoleSortAscending();
20+
21+
Debug.Assert(numbers.SequenceEqual(numbers.OrderBy(i => i)), "Wrong PigeonHole ascending");
22+
}
23+
24+
public static void DoTestDescending()
25+
{
26+
List<int> numbers = new List<int> { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };
27+
numbers.PigeonHoleSortDescending();
28+
29+
Debug.Assert(numbers.SequenceEqual(numbers.OrderByDescending(i => i)), "Wrong PigeonHole descending");
30+
}
31+
}
32+
}

0 commit comments

Comments
 (0)