Repository: TheAlgorithms/Java
Pull request #5298 (2024-07-21 16:46:07)

refactor: cleanup `PigeonholeSort`
This PR adds missed test.

Improve code structure, this should add more readability.

Replaced `ArrayList<Integer>[] pigeonHole = new ArrayList[numOfPigeonholes];` with `List<List<Integer>> pigeonHoles = new ArrayList<>(maxElement + 1);`. 
Because such constructions in Java is generally not considered good practice.

<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5298?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
All modified and coverable lines are covered by tests :white_check_mark:
> Project coverage is 41.17%. Comparing base [(`97d416e`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/97d416e64e0093bd28f64c36c9d29b59137d569e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`fd5905e`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/fd5905e13a93b72749064927a53f27094a255c3e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5298      +/-   ##
============================================
+ Coverage     41.01%   41.17%   +0.16%     
- Complexity     2526     2537      +11     
============================================
  Files           519      519              
  Lines         15444    15442       -2     
  Branches       2947     2943       -4     
============================================
+ Hits           6334     6358      +24     
+ Misses         8816     8789      -27     
- Partials        294      295       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5298?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
index 42fd026b..78d7d81d 100644
--- a/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
+++ b/src/main/java/com/thealgorithms/sorts/PigeonholeSort.java
@@ -1,55 +1,89 @@
 package com.thealgorithms.sorts;
 
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
 
-public class PigeonholeSort {
+public final class PigeonholeSort {
+    private PigeonholeSort() {
+    }
 
-    /*
-        This code implements the pigeonhole sort algorithm for the integer array,
-        but we can also implement this for string arrays too.
-        See https://www.geeksforgeeks.org/pigeonhole-sort/
-    */
-    void sort(Integer[] array) {
-        int maxElement = array[0];
-        for (int element : array) {
-            if (element > maxElement) {
-                maxElement = element;
-            }
-        }
+    /**
+     * Sorts the given array using the pigeonhole sort algorithm.
+     *
+     * @param array the array to be sorted
+     * @throws IllegalArgumentException if any negative integers are found
+     * @return the sorted array
+     */
+    public static int[] sort(int[] array) {
 
-        int numOfPigeonholes = 1 + maxElement;
-        ArrayList<Integer>[] pigeonHole = new ArrayList[numOfPigeonholes];
+        checkForNegativeInput(array);
 
-        for (int k = 0; k < numOfPigeonholes; k++) {
-            pigeonHole[k] = new ArrayList<>();
+        if (array.length == 0) {
+            return array;
         }
 
-        for (int t : array) {
-            pigeonHole[t].add(t);
-        }
+        final int maxElement = Arrays.stream(array).max().orElseThrow();
+        final List<List<Integer>> pigeonHoles = createPigeonHoles(maxElement);
+
+        populatePigeonHoles(array, pigeonHoles);
+        collectFromPigeonHoles(array, pigeonHoles);
+
+        return array;
+    }
 
-        int k = 0;
-        for (ArrayList<Integer> ph : pigeonHole) {
-            for (int elements : ph) {
-                array[k] = elements;
-                k = k + 1;
+    /**
+     * Checks if the array contains any negative integers.
+     *
+     * @param array the array to be checked
+     * @throws IllegalArgumentException if any negative integers are found
+     */
+    private static void checkForNegativeInput(int[] array) {
+        for (final int number : array) {
+            if (number < 0) {
+                throw new IllegalArgumentException("Array contains negative integers.");
             }
         }
     }
 
-    public static void main(String[] args) {
-        PigeonholeSort pigeonholeSort = new PigeonholeSort();
-        Integer[] arr = {8, 3, 2, 7, 4, 6, 8};
-
-        System.out.print("Unsorted order is : ");
-        SortUtils.print(arr);
+    /**
+     * Creates pigeonholes for sorting using an ArrayList of ArrayLists.
+     *
+     * @param maxElement the maximum element in the array
+     * @return an ArrayList of ArrayLists
+     */
+    private static List<List<Integer>> createPigeonHoles(int maxElement) {
+        List<List<Integer>> pigeonHoles = new ArrayList<>(maxElement + 1);
+        for (int i = 0; i <= maxElement; i++) {
+            pigeonHoles.add(new ArrayList<>());
+        }
+        return pigeonHoles;
+    }
 
-        pigeonholeSort.sort(arr);
+    /**
+     * Populates the pigeonholes with elements from the array.
+     *
+     * @param array the array to be sorted
+     * @param pigeonHoles the pigeonholes to be populated
+     */
+    private static void populatePigeonHoles(int[] array, List<List<Integer>> pigeonHoles) {
+        for (int element : array) {
+            pigeonHoles.get(element).add(element);
+        }
+    }
 
-        System.out.print("Sorted order is : ");
-        for (int i = 0; i < arr.length; i++) {
-            assert (arr[i]) <= (arr[i + 1]);
+    /**
+     * Collects sorted elements from the pigeonholes back into the array.
+     *
+     * @param array the array to be sorted
+     * @param pigeonHoles the populated pigeonholes
+     */
+    private static void collectFromPigeonHoles(int[] array, List<List<Integer>> pigeonHoles) {
+        int index = 0;
+        for (final var pigeonHole : pigeonHoles) {
+            for (final int element : pigeonHole) {
+                array[index++] = element;
+            }
         }
-        SortUtils.print(arr);
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java b/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java
new file mode 100644
index 00000000..d1772de8
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/PigeonholeSortTest.java
@@ -0,0 +1,31 @@
+package com.thealgorithms.sorts;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class PigeonholeSortTest {
+
+    @ParameterizedTest
+    @MethodSource("provideArraysForPigeonholeSort")
+    public void testPigeonholeSort(int[] inputArray, int[] expectedArray) {
+        PigeonholeSort.sort(inputArray);
+        assertArrayEquals(expectedArray, inputArray);
+    }
+
+    private static Stream<Arguments> provideArraysForPigeonholeSort() {
+        return Stream.of(Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {4}, new int[] {4}), Arguments.of(new int[] {6, 1, 99, 27, 15, 23, 36}, new int[] {1, 6, 15, 23, 27, 36, 99}), Arguments.of(new int[] {6, 1, 27, 15, 23, 27, 36, 23}, new int[] {1, 6, 15, 23, 23, 27, 27, 36}),
+            Arguments.of(new int[] {5, 5, 5, 5, 5}, new int[] {5, 5, 5, 5, 5}), Arguments.of(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), Arguments.of(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}));
+    }
+
+    @Test
+    public void testWithNegativeNumbers() {
+        assertThrows(IllegalArgumentException.class, () -> PigeonholeSort.sort(new int[] {3, 1, 4, 1, 5, -9}));
+        assertThrows(IllegalArgumentException.class, () -> PigeonholeSort.sort(new int[] {-1}));
+    }
+}