Commit 40ec5eae authored by Fokion Zervoudakis's avatar Fokion Zervoudakis

Add Boyer-Moore majority vote algorithm.

parent 3f9f3511
package misc;
class BoyerM {
/**
Uses the Boyer-Moore majority vote algorithm to find the majority element in
an array of integers
<p>Asymptotic analysis:
<ul>
<li>time_worst=O(n)
<li>space_worst=O(1)
</ul>
@param A an array of {@code n} integers containing a majority element that
appears more than {@code n/2} times
@return the majority element of {@code A}
*/
Integer majorityVote(int[] A) {
int i = 0;
Integer m = null;
for (int n : A) {
if (i == 0) {
m = n;
i++;
} else if (m == n) {
i++;
} else {
i--;
}
}
return m;
}
}
package misc;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
class BoyerMTest {
private BoyerM boyerM;
@BeforeEach
void beforeEach() {
boyerM = new BoyerM();
}
@Test
void itReturnsNullWithZeroElements() {
assertNull(boyerM.majorityVote(new int[0]));
}
@Test
void itReturnsTheMajorityElementWithOneElement() {
assertEquals(1, boyerM.majorityVote(new int[] { 1 }).intValue());
}
@Test
void itReturnsTheMajorityElementWithManyDuplicateElements() {
assertEquals(1, boyerM.majorityVote(new int[] { 1, 1 }).intValue());
}
@Test
void itReturnsTheMajorityElementWithManyUniqueAndDuplicateElements() {
assertEquals(1, boyerM.majorityVote(new int[] { 1, 1, 2 }).intValue());
assertEquals(2, boyerM.majorityVote(new int[] { 1, 2, 2 }).intValue());
}
@Test
void itReturnsTheLastElementWhenAMajorityElementDoesNotExist() {
assertEquals(3, boyerM.majorityVote(new int[] { 1, 2, 3 }).intValue());
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment