The Boyer-Moore Majority Vote Algorithm is an algorithm that finds the majority of an array of numbers , if the majority exists, in time and space.
Tip
This problem can also be solved by Selection Sort in time and space.
Tip
This problem can also be solved by Insertion Sort in time and space.
Tip
This problem can also be solved by Bubble Sort in time and space.
Tip
This problem can also be solved by Merge Sort in time and space.
Tip
This problem can also be solved by Heapsort in time and space.
Tip
This problem can also be solved by Quicksort in time and space.
Tip
This problem can also be solved by Quickselect in time and space.
Algorithm
- Arbitrarily remove two distinct elements, until all the remaining elements have the same value.
Lemma
The value of the remaining elements is the majority of .
Proof
Let denote the number of occurrences of the majority in .
If all the majority elements are removed, at least removes must have been performed, which implies that at least elements are removed.
Since
it follows that more than elements are removed.
By contradiction, it follows that the value of the remaining elements is the majority of .
- Apply the lemma to find the majority.
This algorithm solves the problem in time and space.
int boyer_moore(int n, const std::vector<int> &a) {
int x = 0, c = 0;
for (int i = 0; i < n; i++) {
if (c) {
c += x == a[i] ? 1 : -1;
} else {
x = a[i], c = 1;
}
}
return x;
}