Is it bad idea to use flag variable to search MAX element in array?
- by Boris Treukhov
Over my programming career I formed a habit to introduce a flag variable that indicates that the first comparison has occured, just like Msft does in its linq Max() extension method implementation
public static int Max(this IEnumerable<int> source)
{
if (source == null)
{
throw Error.ArgumentNull("source");
}
int num = 0;
bool flag = false;
foreach (int num2 in source)
{
if (flag)
{
if (num2 > num)
{
num = num2;
}
}
else
{
num = num2;
flag = true;
}
}
if (!flag)
{
throw Error.NoElements();
}
return num;
}
However I have met some heretics lately, who implement this by just starting with the first element and assigning it to result, and oh no - it turned out that STL and Java authors have preferred the latter method.
Java:
public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {
Iterator<? extends T> i = coll.iterator();
T candidate = i.next();
while (i.hasNext()) {
T next = i.next();
if (next.compareTo(candidate) > 0)
candidate = next;
}
return candidate;
}
STL:
template<class _FwdIt> inline
_FwdIt _Max_element(_FwdIt _First, _FwdIt _Last)
{ // find largest element, using operator<
_FwdIt _Found = _First;
if (_First != _Last)
for (; ++_First != _Last; )
if (_DEBUG_LT(*_Found, *_First))
_Found = _First;
return (_Found);
}
Are there any preferences between one method or another? Are there any historical reasons for this? Is one method more dangerous than another?