Sorting array or AssocArrays by value.

Derek Parnell derek at psych.ward
Sun May 4 03:25:17 PDT 2008


On Sun, 4 May 2008 07:58:16 +0000 (UTC), Me Here wrote:

> 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.

Try this 'sort' of thing ...

import std.stdio;
void main()
{
   string[string] theArray;
   theArray["one"] = "neung";
   theArray["two"] = "song";
   theArray["three"] = "saam";
   theArray["four"] = "sii";
   theArray["five"] = "hah";

   foreach(string k; theArray.keys.sort)
      writefln("Key: %10s ==> Data: %s", k, theArray[k]);

}

-- 
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell



More information about the Digitalmars-d mailing list