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

  1. 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 .

  1. 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;
}