Skip to content

Commit

Permalink
Add PigeonHole sort algorithm with test
Browse files Browse the repository at this point in the history
  • Loading branch information
Lucas Lemaire committed Oct 7, 2015
1 parent 81f9a0c commit 96ee270
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
61 changes: 61 additions & 0 deletions Algorithms/Sorting/PigeonHoleSorter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,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++;
}
}
}
}
}
32 changes: 32 additions & 0 deletions MainProgram/AlgorithmsTests/PigeonHoleSortTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Algorithms.Sorting;

namespace C_Sharp_Algorithms.AlgorithmsTests
{
public static class PigeonHoleSortTest
{
public static void DoTest()
{
DoTestAscending();
DoTestDescending();
}

public static void DoTestAscending()
{
List<int> numbers = new List<int> { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };
numbers.PigeonHoleSortAscending();

Debug.Assert(numbers.SequenceEqual(numbers.OrderBy(i => i)), "Wrong PigeonHole ascending");
}

public static void DoTestDescending()
{
List<int> numbers = new List<int> { 23, 42, 4, 16, 8, 15, 3, 9, 55, 0, 34, 12, 2, 46, 25 };
numbers.PigeonHoleSortDescending();

Debug.Assert(numbers.SequenceEqual(numbers.OrderByDescending(i => i)), "Wrong PigeonHole descending");
}
}
}

0 comments on commit 96ee270

Please sign in to comment.