On Sat, 22 Feb 2014 15:57:57 UTC, Marek Novotny <(E-Mail Removed)>
wrote:
>>
> What is so different about these two lines of code that made that
> difference?
>
> my $answer = 0;
> my $answer = $array[0];
In the first case you are setting $answer to an arbitrary value which,
if you are looking for a maximum, needs to be *smaller* than anything
in the data to be searched. 0 works for all positive numbers as all
positive numbers are bigger than 0. But for negative numbers 0 is
*bigger* than all of them - even if there is no 0 in the list as you
found by removing it.
In the second case you are starting with a value you *know* is
actually in the list. It matters not what that value is - just that it
is from the list. You could be really retentive and only search from
the second [1] element onwards, but its hardly worth the bother to
save one compare and an index increment.
HTH
--
Regards
Dave Saville
wrote:
>>
> What is so different about these two lines of code that made that
> difference?
>
> my $answer = 0;
> my $answer = $array[0];
In the first case you are setting $answer to an arbitrary value which,
if you are looking for a maximum, needs to be *smaller* than anything
in the data to be searched. 0 works for all positive numbers as all
positive numbers are bigger than 0. But for negative numbers 0 is
*bigger* than all of them - even if there is no 0 in the list as you
found by removing it.
In the second case you are starting with a value you *know* is
actually in the list. It matters not what that value is - just that it
is from the list. You could be really retentive and only search from
the second [1] element onwards, but its hardly worth the bother to
save one compare and an index increment.
HTH
--
Regards
Dave Saville
Aucun commentaire:
Enregistrer un commentaire