Scala replacement for Arrays.binarySearch?

前端 未结 6 1720
故里飘歌
故里飘歌 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:12

    It not that hard to just write it in scala

      object BSearch {
        def interative[T](array: Array[T], value: T)(implicit arithmetic: Numeric[T]): Int = {
          var left: Int = 0;
          var right: Int = array.length - 1;
          while (right > left) {
            val mid = left + (right - left) / 2
            val comp = arithmetic.compare(array(mid), value)
            if (comp == 0)
              return mid; //negative if test < value
            else if (comp > 0) //list(mid) > value
              right = mid - 1;
            else if (comp < 0) //list(mid) < value
              left = mid + 1;
          }
          -1;
        }
    
    
    BSearch.interative(array, value)
    

提交回复
热议问题