Created
November 6, 2017 15:19
-
-
Save alextanhongpin/f455c55f0020375abe1c808e23fbff79 to your computer and use it in GitHub Desktop.
Boyer–Moore majority vote algorithm. In its simplest form, the algorithm finds a majority element, if there is one: that is, an element that occurs repeatedly for more than half of the elements of the input. However, if there is no majority, the algorithm will not detect that fact, and will still output one of the elements. A versi…
This file contains 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
// Majority vote algorithm | |
// Objective: Given an array of integer, write an algorithm to find the majority element in it (if exist) | |
// Majority element: If an element appears more than n / 2 times in array where n is the size of the array | |
function BoyerMoore () { | |
let i = 0 | |
let m | |
return { | |
vote (x) { | |
if (i === 0) { | |
m = x | |
i = 1 | |
} else if (m === x) { | |
i += 1 | |
} else { | |
i -= 1 | |
} | |
return m | |
}, | |
score (arr) { | |
return { | |
isMajority: arr.filter(v => v === m).length > arr.length / 2, | |
majority: m | |
} | |
} | |
} | |
} | |
const boyerMoore = BoyerMoore() | |
// const arr = [1, 1, 1, 3, 3, 2, 2, 3, 3, 3, 2, 3, 3] | |
const arr = ['a', 'a', 'a', 'c', 'c', 'b', 'b', 'c', 'c', 'c', 'b', 'c', 'c'] | |
arr.forEach(boyerMoore.vote) | |
console.log(boyerMoore.score(arr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment