Fastest way of finding the middle value of a triple?

前端 未结 25 941
庸人自扰
庸人自扰 2020-12-04 12:20

Given is an array of three numeric values and I\'d like to know the middle value of the three.

The question is, what is the fastest way of finding the midd

25条回答
  •  天命终不由人
    2020-12-04 13:03

    If you must find one out of X values satisfying some criteria you have to at least compare that value to each of the X-1 others. For three values this means at least two comparisons. Since this is "find the value that is not the smallest and not the largest" you can get away with only two comparisons.

    You should then concentrate on writing the code so you can very clearly see what goes on and keep it simple. Here this means nested if's. This will allow the JVM to optimize this comparison as much as possible at runtime.

    See the solution provided by Tim (Fastest way of finding the middle value of a triple?) to see an example of this. The many code line does not necessarily turn out to be larger code than nested questionmark-colon's.

提交回复
热议问题