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: Intermediate:
Sort two arrays together

 



dwarnold45
Novice

Jun 29, 2011, 10:44 PM

Post #1 of 4 (748 views)
Sort two arrays together Can't Post

All,

Suppose I have two arrays @a,@b.

When I sort @a in ascending numerical order, I'd like to make an identical sort on @b.

That is if:

@a=(2,5,4,3)

@b=(a,b,c,d)

Then I want:

@a_sort=(2,3,4,5)

@b_sort=(a,d,c,d)

And ideas? Done this one before?

D.


BillKSmith
Veteran

Jun 30, 2011, 4:25 AM

Post #2 of 4 (747 views)
Re: [dwarnold45] Sort two arrays together [In reply to] Can't Post

Combine both arrays into an array-of-arrays. Sort it. Extract the two sorted arrays.


Code
use strict; 
use warnings;
my @a = ( 2, 5, 4, 3);
my @b = ('a', 'b', 'c', 'd');
my @temp = map {[$a[$_],$b[$_]]} 0..$#a;
@temp = sort {$a->[0] <=> $b->[0]} @temp;
@a = map {$_->[0]} @temp;
@b = map {$_->[1]} @temp;
print @a, "\n";
print @b, "\n";

Good Luck,
Bill


rovf
Veteran

Jul 1, 2011, 2:38 AM

Post #3 of 4 (731 views)
Re: [dwarnold45] Sort two arrays together [In reply to] Can't Post


Quote
When I sort @a in ascending numerical order, I'd like to make an identical sort on @b.


Your array @b can't reasonably be sorted in ascending numerical order. It doesn't contain enough numbers...


macareus
New User

Jul 12, 2011, 1:10 AM

Post #4 of 4 (689 views)
Re: [BillKSmith] Sort two arrays together [In reply to] Can't Post

 
If I understand the problem correctly, then this is a
pretty good answer. I would just like to add that,
in the wild (not just a school exercise), this sort of
thing arises when the first array contains small keys,
and the second array contains significantly more
heavy-weight data (larger and/or more complex).

In that case, it is better to create an array of
key,index or key,ref pairs and sort that; then use the
sorted keys to access the values.

 
 


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

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