c++ - Quickly sort 3 values -


i have array of 3 floating-point values , want sort them in ascending order (although order of perhaps sorting algorithm can reversed). calling std::sort seems overkill:

float values[3] = {...}; std::sort(values, values + 3); 

you like:

float sorted[3] = {min(values), values[0] + values[1] + values[2] -     min(values) - max(values), max(values)}; 

but seems plain ugly. adding , subtracting of numbers may change value of middle sorted element. , not work in-place. interesting:

float sorted[3]; /*for(int = 0; < 3; ++ i) { // unroll     sorted[(values[i] > values[0]) + (values[i] > values[1]) +         (values[i] > values[2])] = values[i]; }*/ // broken, not work if 2 or values equal sorted[(values[0] > values[1]) + (values[0] > values[2])] = values[0]; sorted[(values[1] >= values[0]) + (values[1] > values[2])] = values[1]; sorted[(values[2] >= values[0]) + (values[2] >= values[1])] = values[2]; 

but kind of depends on how comparison result can converted integer (probably comparison + flag load instruction). depends on how compiler optimizes away comparison of each element itself, not easy if consider special floating point values. not work inplace either.

#define cswap(a,b) { if(a > b) { float tmp = a; = b; b = tmp; } } while(0) cswap(values[0], values[1]); cswap(values[1], values[2]); cswap(values[0], values[1]); 

there sorting network, suppose not optimal sorting other powers of 2 of elements. 3 elements ... seems there should easy way it, maybe there none.

what minimal , @ same time fast way sort 3 numbers? readability not concern here.

this kind of similar fastest sort of fixed length 6 int array here expect short quick code, sorting 3 values can written in fewer lines of code sorting loop arbitrary number of items.

results:

measured on 100 billions of numbers on intel core i7-2620m , windows 7. visual studio 2008, release, numbers generated rand(), time spent inside subtracted.

std::sort method: 3.510 sec min/max method: 2.964 sec comparison insertion: 2.091 sec (the fixed version, 2.292 buggy one) sort3() jarod42: 1.966 sec sorting network: 1.903 sec 

the general algorithm is:

if (a[0] > a[1])     swap(a[0], a[1]); if (a[0] > a[2])     swap(a[0], a[2]); if (a[1] > a[2])     swap(a[1], a[2]); 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -