How do I “pick and choose” which items in the array I will sort, and make sure I leave the other items alone?
The trick here is to extract a list of the indices of the required subsets; sort those indices according to the appropriate criteria; and then build the sorted array by slicing the sorted array by the subset indices in their original order and the unsorted array by the subset indices in their sorted order.
To illustrate:
data: iOrig iSort 0: e20 0 4 1: b17 2: e04 2 2 3: r16 4: e01 4 0 5: b12 6: e99 6 6 @sorted[ @iOrig ] = @data[ @iSort ]
Thus, the subset from the original data is assigned in their sorted order to the sorted dataset overlaying their original positions; but reordered.
A simple example coded for clarity with lots of scope for optimisation:
#! perl -slw use strict; my @data = qw[ alpha bravo charlie delta east echo exit foxtrot golf hotel india +juliet kilo lima mike november oscar papa quebec romeo sierra tango uniform victor whisk +ey xray yankee zulu ]; my @sortedData; my @rindex = grep{ $data[ $_ ] =~ m[r] } 0 .. $#data; my @rsorted = sort{ $data[ $a ] cmp $data[ $b ] } @rindex; @sortedData[ @rindex ] = @data[ @rsorted ]; my @eindex = grep{ $data[ $_ ] !~ m[r] && $data[ $_ ] =~ m[^e] } 0 .. +$#data; my @esorted = sort{ substr( $data[ $a ], 2, 1 ) cmp substr( $data[ $b +], 2, 1 ) } @eindex; @sortedData[ @eindex ] = @data[ @esorted ]; my @oindex = grep{ $data[ $_ ] !~ m[r] && $data[ $_ ] !~ m[^e] } 0 .. +$#data; my @osorted = sort{ substr( $data[ $b ], -1 ) cmp substr( $data[ $a ], + -1 ) } @oindex; @sortedData[ @oindex ] = @data[ @osorted ]; print for @sortedData; __END__ C:\test>1111596.pl whiskey bravo charlie zulu echo exit east foxtrot juliet kilo tango hotel golf mike yankee november oscar quebec alpha romeo sierra delta uniform victor india xray lima papa
Notes:
In reply to Re: How to perform different sorts on multiple sections of items in the same array
by BrowserUk
in thread How to perform different sorts on multiple sections of items in the same array
by estreb
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |