Created
March 29, 2021 04:23
-
-
Save lilpolymath/edb6edb27d218a4ea0a69c4843920564 to your computer and use it in GitHub Desktop.
An implementation of Moore's Voting Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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