Sorting array or AssocArrays by value.

BCS ao at pathlink.com
Sun May 4 14:08:51 PDT 2008


Reply to Me,

> Hi all,
> 
> A little advice please. Using D v1.028.
> 
> I have (currently) an array of uints. I need to output these sorted,
> which
> .sort does admirably,
> but I need to know what index is associated with each value. How?
> Springing from my own use of the word "associated", I thought that
> maybe I
> should be using
> and associative array for this. But again the problem is that I would
> need to
> sort the keys
> by their associated values.
> In Perl I'd do
> 
> my @array = ...;
> 
> ## Get the indexes ordered by their values
> my @orderIndexes = sort{
> $array[ $a ] <=> $array[ $b ]
> } 0 .. $#array;
> for my $i ( @orderedIndexes ) {
> printf "%d : %d\n2, $i, $array[ $i ];
> }
> Is there anything built-in or in Phobos that will help me here? Or do
> I need to write my own sort?
> 
> Cheers, b.
> 

pack it in ulongs with the index in the lower bits and the value in the upper 
bits.

auto tmp = new ulong[](array.length)

foreach(uint i, uint v; array) tmp[i] = (cast(ulong)v)<<32 | i;
tmp.sort;

// get value of item i
cast(uint)(tmp[i]>>32);

// get index of item i;
cast(uint)(tmp[i] & 0xffff_ffff);





More information about the Digitalmars-d mailing list