Sorting array or AssocArrays by value.
Derek Parnell
derek at psych.ward
Sun May 4 06:40:10 PDT 2008
On Sun, 4 May 2008 13:11:23 +0000 (UTC), Me Here wrote:
> 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
The trick I use for this is to have two AAs. When the set is small,
performance isn't really an issue.
import std.stdio;
void main()
{
int[int] theArray;
theArray[0] = 3;
theArray[1] = 1;
theArray[2] = 8;
theArray[3] = 6;
theArray[4] = 4;
theArray[5] = 9;
theArray[6] = 2;
theArray[7] = 5;
theArray[8] = 7;
int[int] altArray;
foreach(int i; theArray.keys)
{
altArray[ theArray[i] ] = i;
}
foreach(int i; altArray.keys.sort)
writefln("%s - %s", i, altArray[i]);
}
--
Derek Parnell
Melbourne, Australia
skype: derek.j.parnell
More information about the Digitalmars-d
mailing list