Repository: TheAlgorithms/Java
Pull request #5269 (2024-06-30 19:14:13)

refactor: cleanup BeadSort
Cleanup BeadSort and BeadSortTest, adding javadocs.

<!--
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/5269?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.05%. Comparing base [(`208e1e9`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/208e1e99f0ced1a3f3b19371a4f198decf1aac50?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`d9313be`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/d9313bebfa784bd5b62cedeca052adccd41fe8a9?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    #5269      +/-   ##
============================================
- Coverage     40.07%   40.05%   -0.02%     
- Complexity     2464     2466       +2     
============================================
  Files           519      519              
  Lines         15479    15479              
  Branches       2954     2952       -2     
============================================
- Hits           6203     6200       -3     
- Misses         8986     8988       +2     
- Partials        290      291       +1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5269?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/BeadSort.java b/src/main/java/com/thealgorithms/sorts/BeadSort.java
index 101a5c50..1e1c6490 100644
--- a/src/main/java/com/thealgorithms/sorts/BeadSort.java
+++ b/src/main/java/com/thealgorithms/sorts/BeadSort.java
@@ -1,40 +1,59 @@
 package com.thealgorithms.sorts;
 
-// BeadSort Algorithm(wikipedia) : https://en.wikipedia.org/wiki/Bead_sort
-// BeadSort can't sort negative number, Character, String. It can sort positive number only
+import java.util.Arrays;
 
 public class BeadSort {
-    public int[] sort(int[] unsorted) {
-        int[] sorted = new int[unsorted.length];
-        int max = 0;
-        for (int i = 0; i < unsorted.length; i++) {
-            max = Math.max(max, unsorted[i]);
-        }
+    private enum BeadState { BEAD, EMPTY }
 
-        char[][] grid = new char[unsorted.length][max];
-        int[] count = new int[max];
+    /**
+     * Sorts the given array using the BeadSort algorithm.
+     *
+     * @param array The array of non-negative integers to be sorted.
+     * @return The sorted array.
+     * @throws IllegalArgumentException If the array contains negative numbers.
+     */
+    public int[] sort(int[] array) {
+        allInputsMustBeNonNegative(array);
+        return extractSortedFromGrid(fillGrid(array));
+    }
 
-        for (int i = 0; i < unsorted.length; i++) {
-            for (int j = 0; j < max; j++) {
-                grid[i][j] = '-';
-            }
+    private void allInputsMustBeNonNegative(final int[] array) {
+        if (Arrays.stream(array).anyMatch(s -> s < 0)) {
+            throw new IllegalArgumentException("BeadSort cannot sort negative numbers.");
         }
+    }
 
-        for (int i = 0; i < max; i++) {
-            count[i] = 0;
-        }
+    private BeadState[][] fillGrid(final int[] array) {
+        final var maxValue = Arrays.stream(array).max().orElse(0);
+        var grid = getEmptyGrid(array.length, maxValue);
 
-        for (int i = 0; i < unsorted.length; i++) {
+        int[] count = new int[maxValue];
+        for (int i = 0, arrayLength = array.length; i < arrayLength; i++) {
             int k = 0;
-            for (int j = 0; j < unsorted[i]; j++) {
-                grid[count[max - k - 1]++][k] = '*';
+            for (int j = 0; j < array[i]; j++) {
+                grid[count[maxValue - k - 1]++][k] = BeadState.BEAD;
                 k++;
             }
         }
+        return grid;
+    }
+
+    private BeadState[][] getEmptyGrid(final int arrayLength, final int maxValue) {
+        BeadState[][] grid = new BeadState[arrayLength][maxValue];
+        for (int i = 0; i < arrayLength; i++) {
+            for (int j = 0; j < maxValue; j++) {
+                grid[i][j] = BeadState.EMPTY;
+            }
+        }
+
+        return grid;
+    }
 
-        for (int i = 0; i < unsorted.length; i++) {
+    private int[] extractSortedFromGrid(final BeadState[][] grid) {
+        int[] sorted = new int[grid.length];
+        for (int i = 0; i < grid.length; i++) {
             int k = 0;
-            for (int j = 0; j < max && grid[unsorted.length - 1 - i][j] == '*'; j++) {
+            for (int j = 0; j < grid[grid.length - 1 - i].length && grid[grid.length - 1 - i][j] == BeadState.BEAD; j++) {
                 k++;
             }
             sorted[i] = k;


Test patch:
diff --git a/src/test/java/com/thealgorithms/sorts/BeadSortTest.java b/src/test/java/com/thealgorithms/sorts/BeadSortTest.java
index 2ab60b20..d8519147 100644
--- a/src/test/java/com/thealgorithms/sorts/BeadSortTest.java
+++ b/src/test/java/com/thealgorithms/sorts/BeadSortTest.java
@@ -1,42 +1,29 @@
 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 BeadSortTest {
-    // BeadSort can't sort negative number, Character, String. It can sort positive number only
-    private BeadSort beadSort = new BeadSort();
-
-    @Test
-    public void beadSortEmptyArray() {
-        int[] inputArray = {};
-        int[] outputArray = beadSort.sort(inputArray);
-        int[] expectedOutput = {};
-        assertArrayEquals(outputArray, expectedOutput);
-    }
-
-    @Test
-    public void beadSortSingleIntegerArray() {
-        int[] inputArray = {4};
-        int[] outputArray = beadSort.sort(inputArray);
-        int[] expectedOutput = {4};
-        assertArrayEquals(outputArray, expectedOutput);
+    @ParameterizedTest
+    @MethodSource("provideArraysForBeadSort")
+    public void testBeadSort(int[] inputArray, int[] expectedArray) {
+        BeadSort beadSort = new BeadSort();
+        assertArrayEquals(expectedArray, beadSort.sort(inputArray));
     }
 
-    @Test
-    public void bogoSortNonDuplicateIntegerArray() {
-        int[] inputArray = {6, 1, 99, 27, 15, 23, 36};
-        int[] outputArray = beadSort.sort(inputArray);
-        int[] expectedOutput = {1, 6, 15, 23, 27, 36, 99};
-        assertArrayEquals(outputArray, expectedOutput);
+    private static Stream<Arguments> provideArraysForBeadSort() {
+        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 bogoSortDuplicateIntegerArray() {
-        int[] inputArray = {6, 1, 27, 15, 23, 27, 36, 23};
-        int[] outputArray = beadSort.sort(inputArray);
-        int[] expectedOutput = {1, 6, 15, 23, 23, 27, 27, 36};
-        assertArrayEquals(outputArray, expectedOutput);
+    public void testWithNegativeNumbers() {
+        assertThrows(IllegalArgumentException.class, () -> new BeadSort().sort(new int[] {3, 1, 4, 1, 5, -9}));
     }
 }