Most languages have a `max` function, so the core of the loop could be written with just something like: `maxV = max(maxV, v)`
That could be entirely branchless, right?
That could be entirely branchless, right?
[1] https://stackoverflow.com/questions/40196817/what-is-the-ins...
#include <algorithm>
using std::max;
int max_array_func(int values[], size_t values_count)
{
int max_value = values[0];
for (size_t j = 0; j < values_count; j++)
{
max_value = max(max_value, values[j]);
}
return max_value;
}
int max_array_bittwiddling(int values[], size_t values_count)
{
int max_value = values[0];
for (size_t j = 0; j < values_count; j++)
{
int x = max_value;
int y = values[j];
// http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
max_value = x ^ ((x ^ y) & -(x < y));
}
return max_value;
}
int max_array_branch(int values[], size_t values_count)
{
int max_value = values[0];
for (size_t j = 0; j < values_count; j++)
{
if (max_value > values[j])
{
max_value = values[j];
}
}
return max_value;
}