What is the fastest method to check if all elements of an array(preferable integer array) are equal. Till now I have been using the following code:
bool chec
In theory, I would propose this:
bool check_single(const int a[], int n)
{
for (int i = 1; i < n; ++i) {
if (a[0] != a[n]) { return false; }
}
return true;
}
Compared to other (already proposed) versions:
a[0] will be hoisted outside the loop by the compiler, meaning a single array access within the loopa[0] and then looping from a[n]Obviously, it still checks N elements and thus is O(N).