D&C Lug - Home Page
Devon & Cornwall Linux Users' Group

[ Date Index ][ Thread Index ]
[ <= Previous by date / thread ] [ Next by date / thread => ]

Re: [LUG] PHP makes things easy



Simon Waters wrote:

> A common approach to sorting, is to skip it and just return an index of
> the values.

I'm a big fan of that sort of thing.

> i.e. All we need in this circumstance is an array (non associative)
> myindex with values "3","1","0",2" so we can refer to
> alphabet[myindex[0]] and get the first value, alphabet[myindex[1]] to
> get the second. We don't need any hashes as provided by associative
> arrays as far as I can see?

PHP is a bit odd with its array types.

> #!/usr/local/bin/perl
> my @alphabet = ( "562389856", "123521623" , "898234234", "002342444" );
> print "@alphabet \n" ;
> my @myindex = sort { $alphabet[$a] <=> $alphabet[$b] } 0 .. $#alphabet ;
> print "@myindex \n" ;
> print "@alphabet[@myindex]\n";

As an aside, you want to watch leading zeros on number. Somone might
think they're octal :)

> Whether perl actually implements this efficiently underneath is another
> question entirely.

It uses quicksort.

It's worth noting that zero padded numbers can be compared using a
string comparitor, which is the default in perl.

Steve

PS I've just added 2 webmaster in a nutshell 3rd editions, can you
   ditch them. Sorry :)

--
The Mailing List for the Devon & Cornwall LUG
Mail majordomo@xxxxxxxxxxxx with "unsubscribe list" in the
message body to unsubscribe.


Lynx friendly