in reply to How do I record in what order a sort was preformed

Well, it would appear Masem and I have interpreted the question differently.

UPDATE: Erk. No we didnt. /me removes lenscap from eyes. Read Masems reply to my post below. OTOH introducing the ST is never a bad thing, just perhaps not the most appropriate thing ;-)

My interpretation is that you want to sort the list, but be able to determine the elements original positions afterwards. The way to do this is a twist on the Schwartzian Transform.

Basically the idea being that you transform the list into an intermediate form, one that holds the meta info you need, sort as normal and then either use the meta version and or unpack it into the sorted form.

use strict; use warnings; my @array=qw(Q W E R T Y U I O P); my @sorted_meta=sort { $a->[0] cmp $b->[0] } map { [ $array[$_] , $_ ] + } 0..$#array; my @sorted=map { $_->[0] } @sorted_meta; local $,=" "; local $\="\n"; print "Orig: ",@array; print "Meta: ",map { ("[",@{$_},"]") } @sorted_meta; print "Sort: ",@sorted; __END__ Outputs: Orig: Q W E R T Y U I O P Meta: [ E 2 ] [ I 7 ] [ O 8 ] [ P 9 ] [ Q 0 ] [ R 3 ] [ T 4 ] [ U 6 ] + [ W 1 ] [ Y 5 ] Sort: E I O P Q R T U W Y
I took the liberty of making the list be letters so that the output would be clearer. It need not be so by simply changing the 'cmp' into a '<=>'. Actually on that thought you didnt need the int in your sort routine (perl almost always handles those kind of things in a DWIM fashion)

Anyway, hope one of us has managed to answer the question you were asking.. :-)

Yves / DeMerphq
--
When to use Prototypes?

Replies are listed 'Best First'.
Re: Re: How do I record in what order a sort was preformed
by Masem (Monsignor) on Jan 18, 2002 at 00:14 UTC
    You're going to get the ability to get the same result in either fashion. However, for my reply to a similar question on array sorting, merlyn pointed out that the ST is overly heavy for the sorting, and the method that I suggested above was better for getting the sorted indices. Now, with mine, you can rebuild the sorted array via the map I provided, but it's just as easy to do this as well:
    @sorted_indices = sort {...} (0..$#array); # as above @sorted_array = map { $array[$_] } @sorted_indices; #as above my @to_position; $to_position[ sorted_indices[ $_ ] ] = $_ foreach (0..$#array); # thi +s is new
    IMO, I believe this is more lightweight and a bit easier to follow for the given code than using the heavier ST for the same. Not that the ST can't be useful in a similar situation if the comparison values are heavy in terms of calculation times, but here they defintely aren't.

    -----------------------------------------------------
    Dr. Michael K. Neylon - mneylon-pm@masemware.com || "You've left the lens cap of your mind on again, Pinky" - The Brain
    "I can see my house from here!"
    It's not what you know, but knowing how to find it if you don't know that's important