CGI/Perl Guide | Learning Center | Forums | Advertise | Login Site Search: in Perl Guide PerlGuru Forums Learning Ctr
 MAIN INDEX SEARCHPOSTS WHO'S ONLINE LOG IN

Home: Perl Programming Help: Intermediate:
Sort two arrays together

dwarnold45
Novice

Jun 29, 2011, 10:44 PM

Post #1 of 4 (811 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 (810 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 (794 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 (752 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.

 Announcements     PerlGuru Announcements Perl Programming Help     Frequently Asked Questions     Beginner     Intermediate     Advanced     Regular Expressions     mod_perl     DBI     Win32 Programming Help Fun With Perl     Perl Quizzes - Learn Perl the Fun Way     Perl Golf     Perl Poetry Need a Custom or Prewritten Perl Program?     I need a program that...     I Need a Programmer for Freelance Work     Throw Down The Gauntlet General Discussions     General Questions     Feedback     Tutorial/Article Suggestions for The Learning Cent     Internet Security Other Programming Languages     Javascript     PHP

 Search this forum this category all forums for All words Any words Whole Phrase (options) Powered by Gossamer Forum v.1.2.0