i have array of refs me .
$a[0] = [qw( 1 2 3 4 )]; $a[1] = [qw( b c d )]; the 1,2,3,4 website breadcrumbs used navigation (home, profile, contact-us, contact-me-specifically).
now, have sort ladder (and using stable sort in perl 5.8 not option sadly)
the sorting criteria is
- the depth of ladder
- if 2 ladders have same depth, sort them depending on index.
for example, if array contains
$a[0] = [qw( 1 2 3 4 )]; $a[1] = [qw( 1 2 3 )]; then after sort, array should contain
$a[0] = [qw( 1 2 3 )]; $a[1] = [qw( 1 2 3 4 )]; but if arrays :-
$a[0] = [qw( 1 2 3 )]; $a[1] = [qw( b c )]; then after sort,
$a[0] = [qw( 1 2 3 )]; $a[1] = [qw( b c )]; i can't work way tried .
my @sorted_array = sort { @$b <=> @$a || $a <=> $b } @a; can me in this?
the description of data structure (linked list), , implementation in sort routine (arrayrefs) not quite fit together; assume latter.
a non-stable sort can made stable sorting position secondary criterion:
sort { or by_index } @stuff normally, seem want compare array length. able test index, have somehow make index of current element available. can 2 means:
- do schwartzian transform, , annotate each element index. silly.
- sort indices, not elements.
this like:
my @sorted_indices = sort { @{ $array[$b] } <=> @{ $array[$a] } or $a <=> $b } 0 .. $#array; @sorted = @array[@sorted_indices]; # slice what doing $a <=> $b comparing refernces. not guaranteed meaningful.
test of sort:
use test::more; @array = ( [qw/1 2 3/], [qw/a b c/], [qw/foo bar baz qux/], ); @expected = ( [qw/foo bar baz qux/], [qw/1 2 3/], [qw/a b c/], ); ...; # above code is_deeply \@sorted, \@expected; done_testing;
Comments
Post a Comment