Advertisement
Guest User

BinarySearch

a guest
Sep 11th, 2014
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 0.44 KB | None | 0 0
  1. object first {
  2.   def main(args: Array[String]): Unit = {
  3.     println( binarySearch(Array(1,2,3,4), 3) )
  4.   }
  5.  
  6.   def binarySearch(xs: Array[Int], x: Int): Int = {
  7.     def bin(low: Int, high: Int): Int = {
  8.         if (low == high) return -1
  9.  
  10.         val mid = (high + low) / 2
  11.         if (xs(mid) == x) return mid
  12.  
  13.         else if (x > xs(mid)) {
  14.             bin(mid+1, xs.length)
  15.         } else {
  16.             bin(0, mid)
  17.         }
  18.     }
  19.     return bin(0, xs.length)
  20.   }
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement