找到一个三重的中间值的最快的方法?最快、方法

2023-09-11 00:28:34 作者:乱心弃情

由于是三个数值的数组,我想知道这三个的中间值。

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 middle of the three?

我的做法是这样的一种模式 - 因为有三个数字有六种排列:

My approach is this kind of pattern - as there are three numbers there are six permutations:

if (array[randomIndexA] >= array[randomIndexB] &&
    array[randomIndexB] >= array[randomIndexC])

这将是非常好的,如果有人可以帮助我找到一个更优雅的和更快这样做的方式。

推荐答案

如果您正在寻找最有效的解决方案,我会想象它是这样的:

If you are looking for the most efficient solution, I would imagine that it is something like this:

if (array[randomIndexA] > array[randomIndexB]) {
  if (array[randomIndexB] > array[randomIndexC]) {
    return "b is the middle value";
  } else if (array[randomIndexA] > array[randomIndexC]) {
    return "c is the middle value";
  } else {
    return "a is the middle value";
  }
} else {
  if (array[randomIndexA] > array[randomIndexC]) {
    return "a is the middle value";
  } else if (array[randomIndexB] > array[randomIndexC]) {
    return "c is the middle value";
  } else {
    return "b is the middle value";
  }
}

此方法需要至少两个且最多三个比较。它故意忽略了两个值相等的可能性(因为没有你的问题)。如果这是重要的,该方法可以扩展来检查,这也

This approach requires at least two and at most three comparisons. It deliberately ignores the possibility of two values being equal (as did your question): if this is important, the approach can be extended to check this also.