Skip to content

Cleanup BoyerMoore #4951

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
Oct 31, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
modify code to make use of java Optional class
  • Loading branch information
prathameshpowar1910 committed Oct 31, 2023
commit 225a49e7a23f374673fd6759ba0e9de3b38f2a3f
43 changes: 31 additions & 12 deletions src/main/java/com/thealgorithms/others/BoyerMoore.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,54 @@
https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
*/
package com.thealgorithms.others;
import java.util.Optional;

public final class BoyerMoore {
private BoyerMoore() {
}

public static int findmajor(final int[] a) {
private static Optional<Integer> findCandidate(final int[] a) {
int count = 0;
int cand = -1;
for (final var k : a) {
int candidate = -1;
for (final int k : a) {
if (count == 0) {
cand = k;
candidate = k;
count = 1;
} else {
if (k == cand) {
if (k == candidate) {
count++;
} else {
count--;
}
}
}
count = 0;
for (final var j : a) {
if (j == cand) {
return Optional.of(candidate);
}


public static Optional<Integer> findmajor(final int[] a) {
Optional<Integer> candidate = findCandidate(a);

if (candidate.isPresent() && isMajority(candidate.get(), a)) {
return candidate;
} else {
return Optional.empty();
}
}

private static int calculateOccurrences(final int candidate, final int[] a) {
int count = 0;
for (final int j : a) {
if (j == candidate) {
count++;
}
}
if (count > (a.length / 2)) {
return cand;
}
return -1;
return count;
}

private static boolean isMajority(final int candidate, final int[] a) {
int count = calculateOccurrences(candidate, a);
return count > (a.length / 2);
}

}