Help Finding Loop Invariant From For Loop
See this question on Stack Overflow. You should provide reference for an algorithm when you did not write it, at least explain how you came up with it if you "created" it.

Terminology: this question is about finding the majority element of an array.

The invariant at step $i$ is:


A occurs at least in val cells of v[0..i]
The remaining (i + 1 - val) cells can be discarded without changing the majority element.


The algorithm is easy to accept as correct when you understand that if you remove two different elements of the array, then it keeps its majority element.