Sorting array or AssocArrays by value.

Me Here p9e883002 at sneakemail.com
Sun May 4 06:11:23 PDT 2008


Derek Parnell wrote:

> 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]);
> 
> }

I need them ordered by the /values/ not the keys.

Eg. Given, (whether array or hash):

//index/key  0  1  2  3  4  5  6  7 8 
uint a[] =    [ 3, 1,  8, 6, 4, 9, 2, 5, 7 ];

I need to output:
// value  - index
1 - 1
2 - 6
3 = 0
4 - 4
5 - 7
6 - 3
7 - 8
8 - 2
9 - 5

Cheers, b.
-- 




More information about the Digitalmars-d mailing list