Scala replacement for Arrays.binarySearch?

前端 未结 6 1717
故里飘歌
故里飘歌 2020-12-29 03:18

Is there a replacement in Scala for Java\'s int Arrays.binarySearch(Object[] array, object)?

The problem is that Scala\'s Arrays are not covariant, so I

6条回答
  •  失恋的感觉
    2020-12-29 04:15

    @moshe-beeri

    If you were going to write it in Scala, why would you write it in Java in Scala? Why not actually write it in Scala?

    def split(list:List[Char]): (List[Char], List[Char]) = {
        val len = list.size
        (list.slice(0, len/2), list.slice(len/2,len))
    }
    
    def search(target: Char, list: List[Char]):Boolean = {
        list match {
            case Nil => false
            case head :: Nil =>  if (head == target) true else false
            case _ => {
                val c = split(list)
                if (c._1.last >= target) search(target, c._1) else search(target, c._2)
            }
        }
    }
    

提交回复
热议问题