From 61781ca539ffe3514f08b193839687b8c47665b0 Mon Sep 17 00:00:00 2001 From: Mohsin Alam Date: Sun, 3 Aug 2025 17:42:37 +0530 Subject: [PATCH] Refactored binarySearch implementation in scala to return index instead of value. The updated solution is closer to the one given in chapter and is more idiomatic Scala style and standard --- .../scala/01_introduction_to_algorithms.scala | 32 +++++++++---------- 1 file changed, 15 insertions(+), 17 deletions(-) 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) + }