Skip to content

Commit 9c6f3d6

Browse files
authored
Add empty array handling to counting sort (#130)
1 parent d4f1a1d commit 9c6f3d6

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

Algorithms.Tests/Sorters/Integer/CountingSorterTests.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ namespace Algorithms.Tests.Sorters.Integer
88
public static class CountingSorterTests
99
{
1010
[Test]
11-
public static void SortsArray([Random(0, 10000, 100, Distinct = true)]int n)
11+
public static void SortsNonEmptyArray([Random(1, 10000, 100, Distinct = true)]int n)
1212
{
1313
// Arrange
1414
var sorter = new CountingSorter();
@@ -21,5 +21,12 @@ public static void SortsArray([Random(0, 10000, 100, Distinct = true)]int n)
2121
// Assert
2222
Assert.AreEqual(correctArray, testArray);
2323
}
24+
25+
[Test]
26+
public static void SortsEmptyArray()
27+
{
28+
var sorter = new CountingSorter();
29+
sorter.Sort(Array.Empty<int>());
30+
}
2431
}
25-
}
32+
}

Algorithms/Sorters/Integer/CountingSorter.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,14 @@ public class CountingSorter : IIntegerSorter
2525
/// Space complexity: O(n+k), where k is the range of the non-negative key values.
2626
/// </para>
2727
/// </summary>
28-
/// <param name="array">input array.</param>
28+
/// <param name="array">Input array.</param>
2929
public void Sort(int[] array)
3030
{
31+
if (array.Length == 0)
32+
{
33+
return;
34+
}
35+
3136
var max = array.Max();
3237
var min = array.Min();
3338
var count = new int[max - min + 1];

0 commit comments

Comments
 (0)