在Java中对3个值进行排序的最快方法 [英] Fastest way to sort 3 values in Java
问题描述
我必须按正确顺序放置3个值并将它们打印到控制台。
I have to put 3 values in correct order and print them out to the console.
解决方案是将它们放入一个数组然后对它们进行排序,但我记得(从学校时间开始)有更快的比较和订购它们,但我可以找不到正确的比较顺序。
A solution is to put them into an array and then sort them, but I remember (from school times) that there was faster to compare and order them, however I can't find the correct comparison order.
如果$ c $ $ c $,请告诉我如何将3个值与的最小数量进行比较c>陈述?
Could you please show me how to compare 3 values with the minimum number of if
statements?
推荐答案
优化这一点毫无意义。它不会获得任何速度。对于3的O(n!)仍然只有3 * 2 = 6次操作。即使O(2 ^ n)也将是8.您可以真正做任何事情来对这3个值进行排序而不会发现性能上的差异。
There is no point in optimizing this. It will not gain any speed. O(n!) for 3 is still only 3*2 = 6 operations. Even O(2^n) is going to be 8. You could really do whatever it takes to sort these 3 values and not see a difference in performance.
编辑
int a, b, c, min, max, med;//assume values are there for a b c
if( a > b ){
if( a > c ){
max = a;
if( b > c ){
med = b;
min = c;
}else{
med = c;
min = b;
}
}else{
med = a;
max = c;
min = b;
}
}else{
if( b > c ){
max = b;
if( a > c ){
med = a;
min = c;
}else{
med = c;
min = a;
}
}else{
med = b;
max = c;
min = a;
}
}
这篇关于在Java中对3个值进行排序的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!