Repository: TheAlgorithms/Java
Pull request #5280 (2024-07-09 21:55:10)

refactor: cleanup `RadixSort`
Cleanup RadixSort

Adding test

Update DIRECTORY.md

<!--
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/5280?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 [(`57f6580`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/57f65808ad5445f5bd09eb00e58555067655f721?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`b218afa`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/b218afa3a67c92655d502dfaddc6d46032a5473b?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    #5280      +/-   ##
============================================
+ Coverage     40.30%   40.46%   +0.15%     
- Complexity     2481     2489       +8     
============================================
  Files           519      519              
  Lines         15473    15462      -11     
  Branches       2950     2948       -2     
============================================
+ Hits           6237     6257      +20     
+ Misses         8945     8915      -30     
+ Partials        291      290       -1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5280?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).

alxkm: Hello @vil02, all issues for this PR already fixed (also including negative numbers logic remove), could you please review this PR. Thanks.

Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 191158bf..ef7d163a 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -882,6 +882,7 @@
             * [OddEvenSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/OddEvenSortTest.java)
             * [PancakeSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/PancakeSortTest.java)
             * [QuickSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/QuickSortTest.java)
+            * [RadixSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/RadixSortTest.java)
             * [SelectionSortRecursiveTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SelectionSortRecursiveTest.java)
             * [SelectionSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/SelectionSortTest.java)
             * [ShellSortTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/sorts/ShellSortTest.java)
diff --git a/src/main/java/com/thealgorithms/sorts/RadixSort.java b/src/main/java/com/thealgorithms/sorts/RadixSort.java
index a87097bf..f0201a5a 100644
--- a/src/main/java/com/thealgorithms/sorts/RadixSort.java
+++ b/src/main/java/com/thealgorithms/sorts/RadixSort.java
@@ -1,62 +1,98 @@
 package com.thealgorithms.sorts;
 
+import com.thealgorithms.maths.NumberOfDigits;
 import java.util.Arrays;
 
-final class RadixSort {
+/**
+ * This class provides an implementation of the radix sort algorithm.
+ * It sorts an array of nonnegative integers in increasing order.
+ */
+public final class RadixSort {
+    private static final int BASE = 10;
+
     private RadixSort() {
     }
 
-    private static int getMax(int[] arr, int n) {
-        int mx = arr[0];
-        for (int i = 1; i < n; i++) {
-            if (arr[i] > mx) {
-                mx = arr[i];
-            }
+    /**
+     * Sorts an array of nonnegative integers using the radix sort algorithm.
+     *
+     * @param array the array to be sorted
+     * @return the sorted array
+     * @throws IllegalArgumentException if any negative integers are found
+     */
+    public static int[] sort(int[] array) {
+        if (array.length == 0) {
+            return array;
         }
-        return mx;
-    }
 
-    private static void countSort(int[] arr, int n, int exp) {
-        int[] output = new int[n];
-        int i;
-        int[] count = new int[10];
-        Arrays.fill(count, 0);
+        checkForNegativeInput(array);
+        radixSort(array);
+        return array;
+    }
 
-        for (i = 0; i < n; i++) {
-            count[(arr[i] / exp) % 10]++;
+    /**
+     * 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 (int number : array) {
+            if (number < 0) {
+                throw new IllegalArgumentException("Array contains non-positive integers.");
+            }
         }
+    }
 
-        for (i = 1; i < 10; i++) {
-            count[i] += count[i - 1];
+    private static void radixSort(int[] array) {
+        final int max = Arrays.stream(array).max().getAsInt();
+        for (int i = 0, exp = 1; i < NumberOfDigits.numberOfDigits(max); i++, exp *= BASE) {
+            countingSortByDigit(array, exp);
         }
+    }
 
-        for (i = n - 1; i >= 0; i--) {
-            output[count[(arr[i] / exp) % 10] - 1] = arr[i];
-            count[(arr[i] / exp) % 10]--;
-        }
+    /**
+     * A utility method to perform counting sort of array[] according to the digit represented by exp.
+     *
+     * @param array the array to be sorted
+     * @param exp   the exponent representing the current digit position
+     */
+    private static void countingSortByDigit(int[] array, int exp) {
+        int[] count = countDigits(array, exp);
+        accumulateCounts(count);
+        int[] output = buildOutput(array, exp, count);
+        copyOutput(array, output);
+    }
 
-        System.arraycopy(output, 0, arr, 0, n);
+    private static int[] countDigits(int[] array, int exp) {
+        int[] count = new int[BASE];
+        for (int i = 0; i < array.length; i++) {
+            count[getDigit(array[i], exp)]++;
+        }
+        return count;
     }
 
-    private static void radixsort(int[] arr, int n) {
-        int m = getMax(arr, n);
+    private static int getDigit(int number, int position) {
+        return (number / position) % BASE;
+    }
 
-        for (int exp = 1; m / exp > 0; exp *= 10) {
-            countSort(arr, n, exp);
+    private static void accumulateCounts(int[] count) {
+        for (int i = 1; i < BASE; i++) {
+            count[i] += count[i - 1];
         }
     }
 
-    static void print(int[] arr, int n) {
-        for (int i = 0; i < n; i++) {
-            System.out.print(arr[i] + " ");
+    private static int[] buildOutput(int[] array, int exp, int[] count) {
+        int[] output = new int[array.length];
+        for (int i = array.length - 1; i >= 0; i--) {
+            int digit = getDigit(array[i], exp);
+            output[count[digit] - 1] = array[i];
+            count[digit]--;
         }
+        return output;
     }
 
-    public static void main(String[] args) {
-        int[] arr = {170, 45, 75, 90, 802, 24, 2, 66};
-        int n = arr.length;
-        radixsort(arr, n);
-        print(arr, n);
+    private static void copyOutput(int[] array, int[] output) {
+        System.arraycopy(output, 0, array, 0, array.length);
     }
 }
-// Written by James Mc Dermott(theycallmemac)


Test patch:
diff --git a/src/test/java/com/thealgorithms/sorts/RadixSortTest.java b/src/test/java/com/thealgorithms/sorts/RadixSortTest.java
new file mode 100644
index 00000000..24ab52b1
--- /dev/null
+++ b/src/test/java/com/thealgorithms/sorts/RadixSortTest.java
@@ -0,0 +1,30 @@
+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 RadixSortTest {
+    @ParameterizedTest
+    @MethodSource("provideTestCases")
+    public void test(int[] inputArray, int[] expectedArray) {
+        assertArrayEquals(RadixSort.sort(inputArray), expectedArray);
+    }
+
+    private static Stream<Arguments> provideTestCases() {
+        return Stream.of(Arguments.of(new int[] {170, 45, 75, 90, 802, 24, 2, 66}, new int[] {2, 24, 45, 66, 75, 90, 170, 802}), Arguments.of(new int[] {3, 3, 3, 3}, new int[] {3, 3, 3, 3}), Arguments.of(new int[] {9, 4, 6, 8, 14, 3}, new int[] {3, 4, 6, 8, 9, 14}),
+            Arguments.of(new int[] {10, 90, 49, 2, 1, 5, 23}, new int[] {1, 2, 5, 10, 23, 49, 90}), Arguments.of(new int[] {1, 3, 4, 2, 7, 8}, new int[] {1, 2, 3, 4, 7, 8}), Arguments.of(new int[] {}, new int[] {}), Arguments.of(new int[] {1}, new int[] {1}),
+            Arguments.of(new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}), Arguments.of(new int[] {9, 8, 7, 6, 5, 4, 3, 2, 1}, new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}),
+            Arguments.of(new int[] {1000000000, 999999999, 888888888, 777777777}, new int[] {777777777, 888888888, 999999999, 1000000000}), Arguments.of(new int[] {123, 9, 54321, 123456789, 0}, new int[] {0, 9, 123, 54321, 123456789}));
+    }
+
+    @Test
+    public void testWithNegativeNumbers() {
+        assertThrows(IllegalArgumentException.class, () -> RadixSort.sort(new int[] {3, 1, 4, 1, 5, -9}));
+    }
+}