Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork5.7k
Moore's Voting Algorithm - Boyer-Moore Majority Voting Algorithm#1750
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
base:master
Are you sure you want to change the base?
Uh oh!
There was an error while loading.Please reload this page.
Changes fromall commits
a7928f5
8d44461
448415c
193763d
1951f32
File filter
Filter by extension
Conversations
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
/** | ||
* Moore Voting Algorithm to find the majority element in an array | ||
* Majority element is the one that appears more than n/2 times | ||
* geeksforgeeks: https://www.geeksforgeeks.org/boyer-moore-majority-voting-algorithm/ | ||
* @param {Array} arr array of integers | ||
* @returns {Number} majority element or null if no majority exists | ||
*/ | ||
const MooreVotingAlgorithm = (arr) => { | ||
let candidate = null | ||
let count = 0 | ||
// Phase 1: Find the candidate for majority element | ||
for (let num of arr) { | ||
if (count === 0) { | ||
candidate = num | ||
} | ||
count += num === candidate ? 1 : -1 | ||
} | ||
// Phase 2: Verify if the candidate is actually the majority element | ||
count = 0 | ||
for (let num of arr) { | ||
if (num === candidate) { | ||
count++ | ||
} | ||
} | ||
return count > arr.length / 2 ? candidate : null | ||
} | ||
export { MooreVotingAlgorithm } |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
import { MooreVotingAlgorithm } from '../MooreVotingAlgorithm' | ||
describe('Moore Voting Algorithm', () => { | ||
mrinalchauhan marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
it.each([ | ||
[[1, 1, 2, 1, 3, 1, 1], 1], // Majority element 1 | ||
[[2, 2, 2, 2, 5, 5, 5, 2], 2], // Majority element 2 | ||
[[3], 3], // Single element, it's the majority | ||
[[1, 2, 3, 4, 5, 6, 7], null] // No majority element in the array | ||
])('returns %j when given %j', (array, expected) => { | ||
expect(MooreVotingAlgorithm(array)).toEqual(expected) | ||
}) | ||
}) |
Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.
Uh oh!
There was an error while loading.Please reload this page.