MyUtil:二分查找法(Scala)

object BinarySearch  {

  def main(args: Array[String]): Unit = {

    val arr = Array(1, 2, 3, 10, 100, 19999, -1998, 9, 234, 234, 9, 43).sorted
    val index = Binarysearch(arr, 100)
    println("the found value is  " + index)
  }

  def Binarysearch(arr:Array[Int], value:Int):Int={

    var left = 0
    var right = arr.size - 1
    
    while (left <= right){
      var mid = left + ((right - left)>>1)  // 防止溢出, 并且移位操作更高效

      println(s"left:  $left  right : $right  mid: $mid")
      if(arr(mid)> value){
        right = mid -1
      }else if(arr(mid) < value){
        left = mid +1
      }else{
        return  mid               //注意 添加return, scala中只有最后一行才是作为返回值
      }
    }
    -1
  }
}

你可能感兴趣的:(#,MyUtil)