Given the following algorithm (pseudocode):
alg1(A[1,..,n])
i <- 1
candidate <- NULL
count <- 0
while(i <= n)
if(count = 0)
candidate <- A[i]
count <- count + 1
else if(candidate = A[i])
count <- count + 1
else
count <- count - 1
i <- i + 1
return candidate
I need to prove that if a value appears more than $n \over 2$ times (let the value be named $M$) in the array then it will be returned.
$\mathbf{EDIT:}$ here's my 2 attempt. First we assume that the array $A$ contains at least 3 elements (if less then the proof is trivial). The element which appears more than $n/2$ times is $M$ else it's $M'$. Let a two-element combination of $MM'$ or $M'M$ be called $C$. Every time we traverse a $C$ the count
decreases by one.
CASE 1: If the pattern is strictly alternating combinations of type $C$ then the first and the last element must be $M$ (otherwise $M$ will not appear more than $n/2$ times) and this means that after the last iteration the candidate
is $M$.
CASE 2: We can see that after any number of adjacent $C$'s the counter will be $0$ and the candidate
will be either $M$ or $M'$. It is given that more than $n/2$ elements of $M$ do exist in the array, so the number of $C$ combinations must be supplemented by at least $1$ occurrence of $k$ adjacent elements of $M$ either before $C$'s or after $C$'s. If it's after, then the next candidate is $M$ and it will continue to be so as long as we keep traversing $k$ elements of adjacent $M$'s. If it's before than the count
will be at least $1$ before it proceeds to iterate through $C$'s and essentially it'll behave just like CASE 1.
I'm still aware that the proof is not perfect but I feel like it's an improvement. Suggestions/advice is very welcome.
candidate
changes. $\endgroup$