patternjavaMinor
The Boyer-Moore Majority Vote Algorithm
Viewed 0 times
themajorityalgorithmvoteboyermoore
Problem
I have started learning Java recently and was looking into some easy algorithms.
I found the Boyer Moore voting algorithm here.
I am trying to get better at writing good code for my solutions. Please give me your suggestions.
I found the Boyer Moore voting algorithm here.
I am trying to get better at writing good code for my solutions. Please give me your suggestions.
import java.util.Scanner;
public class MajorityVoteAlgorithm {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int size = keyboard.nextInt(); // define size of array
int[] array = new int[size];
// initialize array
for (int i = 0; i array.length / 2)
System.out.println("Majority element is " + candidate);
else
System.out.println("No majority element found");
}
}
}Solution
-
-
The method does two (technically) unrelated jobs: finding the maybe dominant element, and verification that the element is indeed dominant. I recommend splitting it into two methods, for the following reasons:
-
Each loop does an important job and deserves a name.
-
If it is guaranteed that the dominant element exists, verification is a waste of time.
-
If it is guaranteed that the dominant element exists, the requirements can be relaxed even more to an input iterator.
-
Do not print anything from the algorithm. Let
int[] is too strong a requirement. The code does not do any random access. Consider changing an argument from array to stream (this way you may process data not fitting in memory).-
The method does two (technically) unrelated jobs: finding the maybe dominant element, and verification that the element is indeed dominant. I recommend splitting it into two methods, for the following reasons:
-
Each loop does an important job and deserves a name.
-
If it is guaranteed that the dominant element exists, verification is a waste of time.
-
If it is guaranteed that the dominant element exists, the requirements can be relaxed even more to an input iterator.
-
Do not print anything from the algorithm. Let
main handle results.Context
StackExchange Code Review Q#124839, answer score: 7
Revisions (0)
No revisions yet.