Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Numeric sorting WITHOUT <=>

by BillKSmith (Deacon)
on Oct 10, 2012 at 03:31 UTC ( #998121=note: print w/ replies, xml ) Need Help??


in reply to Numeric sorting WITHOUT <=>

Here is one bad way to do it! No comparisons at all.

use strict; use warnings; my %jetsons = ( 7 => 'Judy', 10 => 'Jane', 11 => 'George', 2 => 'Elroy', 100=> 'Rosey', 1 => 'Astro', 19 => 'Mr. Spacely', 22 => 'Mr. Cogswell' ); for my $i (0..100) { print "$i => $jetsons{$i}\n" if exists $jetsons{$i}; }
Bill


Comment on Re: Numeric sorting WITHOUT <=>
Download Code
Replies are listed 'Best First'.
Re^2: Numeric sorting WITHOUT <=>
by Anonymous Monk on Oct 10, 2012 at 03:48 UTC

    One may not know the minimum & maximum values without inspecting to use range operator, so ...

    use strict; use warnings; use List::MoreUtils 'minmax'; my %hash = ( ... ); # Absurdity is to find end values in order to avoid # numeric comparison. my ( $min , $max ) = minmax keys %hash; for my $i ( $min .. $max ) { ... }
Re^2: Numeric sorting WITHOUT <=>
by Marshall (Prior) on Oct 10, 2012 at 04:05 UTC
    Yes, this is indeed a "bad way" to do it! Compared with sort(), this will be slow (20..99) yield no result and it doesn't scale well. And I guess that you would in the general case, have to read every key to find the maximum key value.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://998121]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (17)
As of 2015-07-31 15:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (278 votes), past polls