Advertisement

Finding highest number...

Started by July 16, 2000 09:16 AM
1 comment, last by Goodlife 24 years, 5 months ago
Hi all, I have an operation that happens very frequently. I have four numbers, and I need to determine which one is the highest. Well, right now, I''m just doing four if statements to find the highest. This is not a speed KILLER, but I can''t help but wonder if there''s a logical operator way to do it. Does anyone know a low-cycle way of working with numbers so that you are left with the highest number at the end of it? I''d love to do something like number1(or)number2(or)number3(or)number4, but of course that gives gibberish results. Thanks in advance! -- Goodlife ----------------------------- Those whom the gods would destroy, they first drive mad. --DirectX design team official motto
-- Goodlife-----------------------------Those whom the gods would destroy, they first drive mad.--DirectX design team official motto
This is really a pretty simple solution. My first question is if there is ANY way you can order the insertion of the elements into the array. If you are not searching an ordered array then you are pretty much screwed. Of course you could order it and then search it but with the small number of elements you are using that is hardly worth it.

Now, instead of checking every element with an if statement do something like this.

int Index;
int HighestValueIndex = 0;
int Array[4];

for( Index = 1; Index < NumElementsInArray; Index++ )
{
if ( Array[Index] > Array[HighestValueIndex] )
{
HighestValueIndex = Index;
}
}

Now, Yes I realize that it is starting at index one instead of zero and this is done intentionally because we can assume that at the start of the checking the intial element in the array is always the highest. So what we end up doing is checking elements 2,3 and 4 against element 1. Remember that the element number is different than the index number (hence element 1 = index 0.)


Random Task
Advertisement

If you want speed, using a sequence of ''if'' statements can''t be beat... However, the number of values being tested will have to remain constant. If the number-count varies, do like RandomTask said and use an array and loop-iteration.

This topic is closed to new replies.

Advertisement