Algorithm Steps
- Given an array
arr
of sizen
. - Initialize
count = 0
andcandidate = None
. - Traverse the array:
- → If
count == 0
, setcandidate = current element
. - → If
current element == candidate
, incrementcount
, else decrementcount
. - After the loop,
candidate
is the majority element. - (Optional: Verify candidate by counting its actual occurrences if required.)
Find Majority Element in Array using Boyer-Moore Voting Algorithm Code
Python
JavaScript
Java
C++
C
def majority_element(arr):
count = 0
candidate = None
for num in arr:
if count == 0:
candidate = num
count += (1 if num == candidate else -1)
return candidate
# Sample Input
arr = [2, 2, 1, 1, 1, 2, 2]
print("Majority Element:", majority_element(arr))