Re: efficient max() function from sort



On Wed, May 28, 2008 at 9:17 AM, Ramprasad A Padmanabhan <ram@xxxxxxxxxxxxx>
wrote:


I use sort to give the max of an array something like this

-----
my @z = qw(12 24 67 89 77 91 44 5 10);
my $max = ((reverse sort{$a <=> $b} (@z))[0]);
print "MAX = $max\n";
-----------

but when I am interested only in a single max value, I need not sort the
entire array
Is there a more efficient alternative to this

PS: Posts via nntp to nntp.perl.org appear after a long time
Is there a more preferred way of posting here


Thanks
Ram



--
To unsubscribe, e-mail: beginners-unsubscribe@xxxxxxxx
For additional commands, e-mail: beginners-help@xxxxxxxx
http://learn.perl.org/


just compare one by one to find the max
my @z = qw(12 24 67 89 77 91 44 5 10);
my $max = $z[0];
map { $max = $_ if ($max < $_); } @z;
print $max;

or use List::Util which provides max subroutine


Relevant Pages

  • Re: Need help sorting by specific fields in file.
    ... > I have a file that I need to sort and currently I am just ... You're sorting an array. ... grab the first 6 characters off of all of them, ... That's just a basic grab the first 6 numbers and compare approach. ...
    (perl.beginners)
  • Re: sort function
    ... I've got an array. ... Now I want to sort this ... Is there a funkionality like that available withinf fortran? ... subroutine sort_matrix ...
    (comp.lang.fortran)
  • Re: An inefficiency in Array.Sort
    ... use a temporary array, and Array.Sort is an in-place sort. ... they repeatedly compare ato a. ... former really makes no sense at all, especially presuming a QuickSort ... It is possible that the sort algorithm loses track of the original array ...
    (microsoft.public.dotnet.languages.vb)
  • Re: "Sorting" assignment
    ... And many others prefer to call partition exchange because "quicksort" ... bin B depending on whether it is greater than, ... If the array is already sorted, this means that you end up ... attempt to sort them. ...
    (comp.programming)
  • Re: Fortran templates
    ... into "having a method which sorts the client-side array". ... have to explicitly define the type of data to compare. ... code, whereas in my Fortran quicksort-with-callbacks, you must define ... However, if you want to sort *strings*, you will have to define ...
    (comp.lang.fortran)