diff --git a/01_introduction_to_algorithms/scala/01_introduction_to_algorithms.scala b/01_introduction_to_algorithms/scala/01_introduction_to_algorithms.scala index 30edf68e..ee5b984f 100644 --- a/01_introduction_to_algorithms/scala/01_introduction_to_algorithms.scala +++ b/01_introduction_to_algorithms/scala/01_introduction_to_algorithms.scala @@ -1,18 +1,16 @@ -def binarySearch(list: List[Int], item: Int): Int = { - if(list.isEmpty) { println("Item not found"); return 0 } - val guessIndex = (list.length) / 2 - val guess = list(guessIndex) - if(item == guess) guess - else if(item < guess){ - val halfList = list.take(list.length / 2) - binarySearch(halfList, item) - } - else { - val halfList = list.drop(1 + (list.length / 2)) - binarySearch(halfList, item) - } -} +def binarySearch(numbers : Vector[Int], item : Int) : Option[Int] = { + @tailrec + def search(low : Int, high : Int) : Option[Int] = { + println(s"low = $low ; high = $high") + if (low > high) None + else{ + val mid = (low + high)/2 + val guess = numbers(mid) + if (guess == item) Some(mid) + else if (guess > item) search(low, mid - 1) + else search(mid + 1, high) + } + } -val myList = List(1,3,5,7,9) -println(binarySearch(myList, 3)) -println(binarySearch(myList, -1)) + search(0, numbers.length - 1) + }