I have created the algorithm below...
String A = v[0];
int val = 1;
for (int i = 1; i < v.length; i++) {
if (val == 0) {
A = v[i];
val++;
} else if (v[i].equals(A))
val++;
else
val--;
}
The goal of the algorithm is to find the item that occurs in more than half the array.
Let v = {"one", "two", "one", "three", "one", "two", "two", "one", "one"}
The string "one" occurs 5 out of 9 times. So, at the end of the loop, the String A will be equal to "one".
I'm lost as to how to derive a loop invariant from this. Could someone provide me with some direction?
{"one","two","three"}$\endgroup$