Skip to content

Instantly share code, notes, and snippets.

@lilpolymath
Created March 29, 2021 04:23
Show Gist options
  • Save lilpolymath/edb6edb27d218a4ea0a69c4843920564 to your computer and use it in GitHub Desktop.
Save lilpolymath/edb6edb27d218a4ea0a69c4843920564 to your computer and use it in GitHub Desktop.
An implementation of Moore's Voting Algorithm
export const isMajority = (arr, candidate_index) => {
const candidate = arr[candidate_index];
let count = 0;
const halfSize = arr.length / 2;
for (let i = 0; i < arr.length; i++) {
if (candidate === arr[i]) {
count++;
}
}
if (count > halfSize) {
return candidate;
} else {
return false;
}
};
export const majorityElement = (arr) => {
let count = 1;
let candidate_index = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] === arr[candidate_index]) {
count++;
} else {
count--;
}
if (count === 0) {
candidate_index = i;
count = 1;
}
}
return candidate_index;
};
const array = [2, 2, 3, 4];
const index = majorityElement(array);
const result = isMajority(array, index);
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment