在Scala中计算最多5的中位数

Dan*_*ral 2 algorithm scala median

所以,在回答其他一些问题时,我偶然发现计算中位数为5的必要性.现在,在另一种语言中有一个类似的问题,但是我想要一个Scala算法,我不确定我是否满意我的.

Rex*_*err 5

这是一个不可变的Scala版本,具有最小的比较数(6)并且看起来不太丑:

def med5(five: (Int,Int,Int,Int,Int)) = {

  // Return a sorted tuple (one compare)
  def order(a: Int, b: Int) = if (a<b) (a,b) else (b,a)

  // Given two self-sorted pairs, pick the 2nd of 4 (two compares)
  def pairs(p: (Int,Int), q: (Int,Int)) = {
    (if (p._1 < q._1) order(p._2,q._1) else order(q._2,p._1))._1
  }

  // Strategy is to throw away smallest or second smallest, leaving two self-sorted pairs
  val ltwo = order(five._1,five._2)
  val rtwo = order(five._4,five._5)
  if (ltwo._1 < rtwo._1) pairs(rtwo,order(ltwo._2,five._3))
  else pairs(ltwo,order(rtwo._2,five._3))
}
Run Code Online (Sandbox Code Playgroud)

编辑:根据丹尼尔的要求,这里有一个修改,适用于所有尺寸和数组,所以它应该是有效的.我不能说它漂亮,所以效率是下一个最好的东西.(> 200M中位数/快于我的不可改变的版本上述(对于5秒的长度为5的预分配的阵列,这比丹尼尔的版本快略超过100倍,和8倍)).

def med5b(five: Array[Int]): Int = {

  def order2(a: Array[Int], i: Int, j: Int) = {
    if (a(i)>a(j)) { val t = a(i); a(i) = a(j); a(j) = t }
  }

  def pairs(a: Array[Int], i: Int, j: Int, k: Int, l: Int) = {
    if (a(i)<a(k)) { order2(a,j,k); a(j) }
    else { order2(a,i,l); a(i) }
  }

  if (five.length < 2) return five(0)
  order2(five,0,1)
  if (five.length < 4) return (
    if (five.length==2 || five(2) < five(0)) five(0)
    else if (five(2) > five(1)) five(1)
    else five(2)
  )
  order2(five,2,3)
  if (five.length < 5) pairs(five,0,1,2,3)
  else if (five(0) < five(2)) { order2(five,1,4); pairs(five,1,4,2,3) }
  else { order2(five,3,4); pairs(five,0,1,3,4) }
}
Run Code Online (Sandbox Code Playgroud)