Majority Vote Finds The Dominant Element
Majority vote tracks a candidate and counter in one pass, then verifies the candidate truly exceeds half the input before returning it.
Code
// Boyer-Moore 投票:候选与计数随迭代更新,扫描结束再做过半验证
fn majority<T: PartialEq + Copy>(items: &[T]) -> Option<T> {
let mut candidate = None;
let mut votes = 0usize;
for &item in items {
if votes == 0 {
candidate = Some(item);
votes = 1;
} else if candidate == Some(item) {
votes += 1;
} else {
votes -= 1;
}
}
// 验证:候选必须真的出现超过一半,否则返回 None
candidate.filter(|c| items.iter().filter(|&x| x == c).count() * 2 > items.len())
}
fn main() {
let ballots = ["go", "rust", "rust", "go", "rust"];
println!("majority: {:?}", majority(&ballots));
let split = ["go", "rust", "go", "rust"];
println!("no majority: {:?}", majority(&split));
}Inside the snippet
Structurally, expect the functions majority and main and nothing else.
Repetition is confined to for &item in items — the rest of the file is straight-line.
Using it
The demo output is labeled (majority:, no majority:), so every printed line maps back to its originating operation.
The entry point wires majority together — run it once and the whole demo flows.
Key statements
candidate.filter(|c| items.iter().filter(|&x| x == c).count() * 2 > items.len())
}
let mut candidate = None;
candidate = Some(item);
Interactive Tools for This Topic
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Majority Vote Finds The Dominant Element print when run?
- Run it as a complete program — the output lines carry labels such as `majority:`, `no majority:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.