8000 Merge pull request #1177 from pranavkhapra/PigeonHoleSorter · kishore-code/Algorithms-1@ccc21fa · GitHub
[go: up one dir, main page]

Skip to content

Commit ccc21fa

Browse files
authored
Merge pull request VAR-solutions#1177 from pranavkhapra/PigeonHoleSorter
Pigeon hole sorter also known as Count Sort
2 parents d8ede12 + 9200a15 commit ccc21fa

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
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+
}

0 commit comments

Comments
 (0)
0