Repository: TheAlgorithms/Java
Pull request #5395 (2024-08-25 22:11:14)

refactor: `BoyerMoore`
Class cleanup.
Readability improvements.

<!--
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/5395?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `90.00000%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 47.62%. Comparing base [(`7e9cdad`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/7e9cdad3ee205084822a46b45a21b2ed4467432e?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`d00616e`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/d00616ee2599ace3849e55bcb5f9b8e04e88d3de?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).

| [Files](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5395?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...main/java/com/thealgorithms/others/BoyerMoore.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5395?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fothers%2FBoyerMoore.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9vdGhlcnMvQm95ZXJNb29yZS5qYXZh) | 90.00% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5395?src=pr&el=tree&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    #5395      +/-   ##
============================================
+ Coverage     47.60%   47.62%   +0.01%     
- Complexity     2944     2946       +2     
============================================
  Files           524      524              
  Lines         15312    15311       -1     
  Branches       2906     2906              
============================================
+ Hits           7290     7292       +2     
+ Misses         7720     7718       -2     
+ Partials        302      301       -1     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5395?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/others/BoyerMoore.java b/src/main/java/com/thealgorithms/others/BoyerMoore.java
index e67427de..3fb97724 100644
--- a/src/main/java/com/thealgorithms/others/BoyerMoore.java
+++ b/src/main/java/com/thealgorithms/others/BoyerMoore.java
@@ -1,54 +1,81 @@
-/* this Code is the illustration of Boyer moore's voting algorithm to
-find the majority element is an array that appears more than n/2 times in an array
-where "n" is the length of the array.
-For more information on the algorithm refer
-https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
- */
 package com.thealgorithms.others;
 import java.util.Optional;
 
+/**
+ * Utility class implementing Boyer-Moore's Voting Algorithm to find the majority element
+ * in an array. The majority element is defined as the element that appears more than n/2 times
+ * in the array, where n is the length of the array.
+ *
+ * For more information on the algorithm, refer to:
+ * https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
+ */
 public final class BoyerMoore {
     private BoyerMoore() {
     }
 
-    public static Optional<Integer> findMajor(final int[] a) {
-        final var candidate = findCandidate(a);
-        final var count = countOccurrences(candidate, a);
-        if (isMajority(count, a.length)) {
+    /**
+     * Finds the majority element in the given array if it exists.
+     *
+     * @param array the input array
+     * @return an Optional containing the majority element if it exists, otherwise an empty Optional
+     */
+    public static Optional<Integer> findMajorityElement(int[] array) {
+        if (array == null || array.length == 0) {
+            return Optional.empty();
+        }
+
+        int candidate = findCandidate(array);
+        int count = countOccurrences(candidate, array);
+
+        if (isMajority(count, array.length)) {
             return Optional.of(candidate);
         }
         return Optional.empty();
     }
 
-    private static int findCandidate(final int[] a) {
+    /**
+     * Identifies the potential majority candidate using Boyer-Moore's Voting Algorithm.
+     *
+     * @param array the input array
+     * @return the candidate for the majority element
+     */
+    private static int findCandidate(final int[] array) {
         int count = 0;
         int candidate = -1;
-        for (final var k : a) {
+        for (int value : array) {
             if (count == 0) {
-                candidate = k;
-                count = 1;
-            } else {
-                if (k == candidate) {
-                    count++;
-                } else {
-                    count--;
-                }
+                candidate = value;
             }
+            count += (value == candidate) ? 1 : -1;
         }
         return candidate;
     }
 
-    private static int countOccurrences(final int candidate, final int[] a) {
+    /**
+     * Counts the occurrences of the candidate element in the array.
+     *
+     * @param candidate the candidate element
+     * @param array the input array
+     * @return the number of times the candidate appears in the array
+     */
+    private static int countOccurrences(final int candidate, final int[] array) {
         int count = 0;
-        for (final var j : a) {
-            if (j == candidate) {
+        for (int value : array) {
+            if (value == candidate) {
                 count++;
             }
         }
         return count;
     }
 
-    private static boolean isMajority(final int count, final int totalCount) {
+    /**
+     * Determines if the count of the candidate element is more than n/2, where n is the length of the array.
+     *
+     * @param count the number of occurrences of the candidate
+     * @param totalCount the total number of elements in the array
+     * @return true if the candidate is the majority element, false otherwise
+     */
+    private static boolean isMajority(int count, int totalCount) {
         return 2 * count > totalCount;
     }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/others/BoyerMooreTest.java b/src/test/java/com/thealgorithms/others/BoyerMooreTest.java
index b6620793..8416535b 100644
--- a/src/test/java/com/thealgorithms/others/BoyerMooreTest.java
+++ b/src/test/java/com/thealgorithms/others/BoyerMooreTest.java
@@ -11,7 +11,7 @@ public class BoyerMooreTest {
     @ParameterizedTest
     @MethodSource("inputStreamWithExistingMajority")
     void checkWhenMajorityExists(int expected, int[] input) {
-        Assertions.assertEquals(expected, BoyerMoore.findMajor(input).get());
+        Assertions.assertEquals(expected, BoyerMoore.findMajorityElement(input).get());
     }
 
     private static Stream<Arguments> inputStreamWithExistingMajority() {
@@ -21,7 +21,7 @@ public class BoyerMooreTest {
     @ParameterizedTest
     @MethodSource("inputStreamWithoutMajority")
     void checkWhenMajorityExists(int[] input) {
-        Assertions.assertFalse(BoyerMoore.findMajor(input).isPresent());
+        Assertions.assertFalse(BoyerMoore.findMajorityElement(input).isPresent());
     }
 
     private static Stream<Arguments> inputStreamWithoutMajority() {