diff --git a/src/main/java/com/thealgorithms/others/BoyerMoore.java b/src/main/java/com/thealgorithms/others/BoyerMoore.java index 09235b52..d9d5b5d0 100644 --- a/src/main/java/com/thealgorithms/others/BoyerMoore.java +++ b/src/main/java/com/thealgorithms/others/BoyerMoore.java @@ -6,27 +6,28 @@ https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm */ package com.thealgorithms.others; -import java.util.*; +public final class BoyerMoore { + private BoyerMoore() { + } -public class BoyerMoore { - - public static int findmajor(int[] a) { + public static int findmajor(final int[] a) { int count = 0; int cand = -1; - for (int i = 0; i < a.length; i++) { + for (final var k : a) { if (count == 0) { - cand = a[i]; + cand = k; count = 1; } else { - if (a[i] == cand) { + if (k == cand) { count++; } else { count--; } } } - for (int i = 0; i < a.length; i++) { - if (a[i] == cand) { + count = 0; + for (final var j : a) { + if (j == cand) { count++; } } @@ -35,15 +36,4 @@ public class BoyerMoore { } return -1; } - - public static void main(String[] args) { - Scanner input = new Scanner(System.in); - int n = input.nextInt(); - int[] a = new int[n]; - for (int i = 0; i < n; i++) { - a[i] = input.nextInt(); - } - System.out.println("the majority element is " + findmajor(a)); - input.close(); - } } diff --git a/src/test/java/com/thealgorithms/others/BoyerMooreTest.java b/src/test/java/com/thealgorithms/others/BoyerMooreTest.java new file mode 100644 index 00000000..b614c140 --- /dev/null +++ b/src/test/java/com/thealgorithms/others/BoyerMooreTest.java @@ -0,0 +1,22 @@ +package com.thealgorithms.others; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.stream.Stream; +import org.junit.jupiter.api.Assertions; +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 BoyerMooreTest { + + @ParameterizedTest + @MethodSource("inputStream") + void numberTests(int expected, int[] input) { + Assertions.assertEquals(expected, BoyerMoore.findmajor(input)); + } + + private static Stream inputStream() { + return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 2}), Arguments.of(10, new int[] {10, 10, 20}), Arguments.of(10, new int[] {10, 20, 10}), Arguments.of(10, new int[] {20, 10, 10}), Arguments.of(-1, new int[] {10, 10, 20, 20, 30, 30}), Arguments.of(4, new int[] {1, 4, 2, 4, 4, 5, 4})); + } +}