CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Sorting an array !

 



seriousfun
Novice

Jun 10, 2000, 2:45 PM

Post #1 of 3 (511 views)
Sorting an array ! Can't Post

I have a script which produces its search results in an array holding the various fields in format like fieldone|fieldtwo|fieldthree|etc...

My question is how do I sort the array into numerical order of field one at the same time keeping all other fields in the array attached to field one ( in effect all field sorted with field one)

All help is warmly appreciated.


dws
Deleted

Jun 11, 2000, 10:06 AM

Post #2 of 3 (511 views)
Re: Sorting an array ! [In reply to] Can't Post

Use a "Schwartzian Transform". The idea is to turn each datum into an anonymous array that contains the initial datum plus some aspect of it (in this case, the leading digit), then sort the anonymous arrays based on the aspect, then turn the anonymous arrays back into the original datum.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

@data = ("1|foo", "10|baz", "5|bar");

@sorted = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [ $_, (split /\|/, $_)[0] ] }
@data;

print join "\n", @sorted;</pre><HR></BLOCKQUOTE>




dws
Deleted

Jun 11, 2000, 10:19 AM

Post #3 of 3 (511 views)
Re: Sorting an array ! [In reply to] Can't Post

On second thought, the Schwartzian Transform isn't a beginner move. You might be better off with something like this, which takes the simple approach of building a hash keyed by the id from each record, then sorting the keys.
<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

data = ("1|foo", "10|baz", "5|bar");
%by_id = ();

foreach ( @data ) {
/^(\d+)\|/;
$by_id{$1} = $_;
}

foreach ( sort { $a <=> $b } keys %by_id ) {
print $by_id{$_}, "\n";
}</pre><HR></BLOCKQUOTE>

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives