[OT] Lower and upper median of 4

Timon Gehr via Digitalmars-d digitalmars-d at puremagic.com
Sat Nov 26 13:36:57 PST 2016


On 26.11.2016 22:11, Andrei Alexandrescu wrote:
> On 11/26/2016 03:19 PM, Timon Gehr wrote:
>>
>> The following code (which I found using a quick brute-force search) uses
>> at most 4 comparisons.
>>
>>
>> int median(bool leanRight)(int[4] a){
>>     static if(leanRight){
>>         return
>> a[a[0]<a[1]?a[2]<a[3]?a[1]<a[3]?a[1]<a[2]?2:1:a[0]<a[3]?3:0:a[1]<a[2]?a[1]<a[3]?3:1:a[0]<a[2]?2:0:a[2]<a[3]?a[0]<a[3]?a[0]<a[2]?2:0:a[1]<a[3]?3:1:a[0]<a[2]?a[0]<a[3]?3:0:a[1]<a[2]?2:1];
>>
>>
>>     }else{
>>         return
>> a[a[0]<a[1]?a[2]<a[3]?a[0]<a[2]?a[1]<a[2]?1:2:a[0]<a[3]?0:3:a[0]<a[3]?a[1]<a[3]?1:3:a[0]<a[2]?0:2:a[2]<a[3]?a[1]<a[2]?a[0]<a[2]?0:2:a[1]<a[3]?1:3:a[1]<a[3]?a[0]<a[3]?0:3:a[1]<a[2]?1:2];
>>
>>
>>     }
>> }
>
> Thanks! Sorry, I forgot to mention partitioning around the lower/upper
> median is also needed. It seems that changes the tradeoff space. -- Andrei

Did you see the suggestion to make the leanLeft/leanRight cases 
symmetric, such that both use at most 4 branches?


More information about the Digitalmars-d mailing list