Repository: TheAlgorithms/Java
Pull request #5287 (2024-07-12 08:09:14)

feat: `CountingSort` implementation
CountingSort implementation.

Previous discussion in this PR
https://github.com/TheAlgorithms/Java/pull/5275

<!--
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/5287?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 40.46%. Comparing base [(`87e6184`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/87e6184494b40900a9e1b31c66032840ab373dbc?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`884641e`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/884641e153ea89eea784547c1d0d6a59e7a16e89?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    #5287      +/-   ##
============================================
+ Coverage     40.41%   40.46%   +0.05%     
- Complexity     2485     2489       +4     
============================================
  Files           518      519       +1     
  Lines         15451    15466      +15     
  Branches       2948     2951       +3     
============================================
+ Hits           6244     6259      +15     
  Misses         8916     8916              
  Partials        291      291              
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5287?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/DIRECTORY.md b/DIRECTORY.md
index 2b1f4396..aa100502 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -494,6 +494,7 @@
             * [BucketSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/BucketSort.java)
             * [CircleSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/CircleSort.java)
             * [CocktailShakerSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/CocktailShakerSort.java)
+            * [CountingSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/CountingSort.java)
             * [CombSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/CombSort.java)
             * [CycleSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/CycleSort.java)
             * [DNFSort](https://github.com/TheAlgorithms/Java/blob/master/src/main/java/com/thealgorithms/sorts/DNFSort.java)
@@ -862,6 +863,7 @@
             * [BucketSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/BucketSortTest.java)
             * [CircleSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CircleSortTest.java)
             * [CocktailShakerSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CocktailShakerSortTest.java)
+            * [CountingSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CountingSortTest.java)
             * [CombSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/CombSortTest.java)
             * [DualPivotQuickSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/DualPivotQuickSortTest.java)
             * [DutchNationalFlagSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/DutchNationalFlagSortTest.java)
diff --git a/src/main/java/com/thealgorithms/sorts/CountingSort.java b/src/main/java/com/thealgorithms/sorts/CountingSort.java
new file mode 100644
index 00000000..5d542050
--- /dev/null
+++ b/src/main/java/com/thealgorithms/sorts/CountingSort.java
@@ -0,0 +1,60 @@
+package com.thealgorithms.sorts;
+
+import java.util.Arrays;
+
+/**
+ * A standard implementation of the Counting Sort algorithm for integer arrays.
+ * This implementation has a time complexity of O(n + k), where n is the number
+ * of elements in the input array and k is the range of the input.
+ * It works only with integer arrays.
+ *
+ * The space complexity is O(k), where k is the range of the input integers.
+ *
+ * Note: This implementation handles negative integers as it
+ * calculates the range based on the minimum and maximum values of the array.
+ *
+ */
+public final class CountingSort {
+    private CountingSort() {
+    }
+
+    /**
+     * Sorts an array of integers using the Counting Sort algorithm.
+     *
+     * @param array the array to be sorted
+     * @return the sorted array
+     */
+    public static int[] sort(int[] array) {
+        if (array.length == 0) {
+            return array;
+        }
+        final var stats = Arrays.stream(array).summaryStatistics();
+        final int min = stats.getMin();
+        int[] count = computeHistogram(array, min, stats.getMax() - min + 1);
+        toCumulative(count);
+        return reconstructSorted(count, min, array);
+    }
+
+    private static int[] computeHistogram(final int[] array, final int shift, final int spread) {
+        int[] res = new int[spread];
+        for (final var value : array) {
+            res[value - shift]++;
+        }
+        return res;
+    }
+
+    private static void toCumulative(int[] count) {
+        for (int i = 1; i < count.length; i++) {
+            count[i] += count[i - 1];
+        }
+    }
+
+    private static int[] reconstructSorted(final int[] cumulativeCount, final int shift, final int[] array) {
+        int[] res = new int[array.length];
+        for (int i = array.length - 1; i >= 0; i--) {
+            res[cumulativeCount[array[i] - shift] - 1] = array[i];
+            cumulativeCount[array[i] - shift]--;
+        }
+        return res;
+    }
+}


Test patch:
diff --git a/src/test/java/com/thealgorithms/sorts/CountingSortTest.java b/src/test/java/com/thealgorithms/sorts/CountingSortTest.java
new file mode 100644
index 00000000..2426de6f
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/CountingSortTest.java
@@ -0,0 +1,27 @@
+package com.thealgorithms.sorts;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+
+import java.util.stream.Stream;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
+
+public class CountingSortTest {
+
+    record TestCase(int[] inputArray, int[] expectedArray) {
+    }
+
+    static Stream<TestCase> provideTestCases() {
+        return Stream.of(new TestCase(new int[] {}, new int[] {}), new TestCase(new int[] {4}, new int[] {4}), new TestCase(new int[] {6, 1, 99, 27, 15, 23, 36}, new int[] {1, 6, 15, 23, 27, 36, 99}), new TestCase(new int[] {6, 1, 27, 15, 23, 27, 36, 23}, new int[] {1, 6, 15, 23, 23, 27, 27, 36}),
+            new TestCase(new int[] {5, 5, 5, 5, 5}, new int[] {5, 5, 5, 5, 5}), new TestCase(new int[] {1, 2, 3, 4, 5}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5}), new TestCase(new int[] {3, -1, 4, 1, 5, -9}, new int[] {-9, -1, 1, 3, 4, 5}),
+            new TestCase(new int[] {0, 0, 0, 0}, new int[] {0, 0, 0, 0}), new TestCase(new int[] {3, 3, -1, -1, 2, 2, 0, 0}, new int[] {-1, -1, 0, 0, 2, 2, 3, 3}), new TestCase(new int[] {-3, -2, -1, -5, -4}, new int[] {-5, -4, -3, -2, -1}),
+            new TestCase(new int[] {1000, 500, 100, 50, 10, 5, 1}, new int[] {1, 5, 10, 50, 100, 500, 1000}), new TestCase(new int[] {4, -5, 10, 0}, new int[] {-5, 0, 4, 10}));
+    }
+
+    @ParameterizedTest
+    @MethodSource("provideTestCases")
+    public void testCountingSortException(TestCase testCase) {
+        int[] outputArray = CountingSort.sort(testCase.inputArray);
+        assertArrayEquals(testCase.expectedArray, outputArray);
+    }
+}