Sorting array or AssocArrays by value.
Xinok
xnknet at gmail.com
Sun May 4 07:11:38 PDT 2008
Me Here wrote:
> Derek Parnell wrote:
>
>> 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]);
>>
>>
>> }
>
> Problem: That works fine if the values in the origianl array are unique.
> But in this case thay are not. This is frequency information.
> The index to the array is numeric value of words in a file.
> The values are counts of the occurance of that value in the file,
>
> A truncated sample showing the first of many duplicates.
> 0 : 5780646
> 1 : 219016
> 2 : 138623
> 3 : 100037
> 4 : 89876
> 5 : 61845
> 6 : 60890
> 7 : 41191
> 8 : 60231
> 9 : 36885 *
> ...
> 70 : 13069
> 71 : 36885 *
> 72 : 16121
> 73 : 10721
>
> I need to out put this as either:
> ...
> 36885: 9, 70
> ...
> or
> 36885: 9
> 36885: 70
>
> Cheers, b.
I suggest you write your own sort function which will sort two arrays
accordingly. Shell sort would probably be the easiest to implement this for.
More information about the Digitalmars-d
mailing list