Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,873 questions

51,797 answers

573 users

How to implement recursive binary search in Scala

1 Answer

0 votes
object RecursiveBinarySearch {
  def recursiveBinarySearch(arr: Array[Int], left: Int, right: Int, toFind: Int): Int = {
    if (right >= left) {
      val mid = left + (right - left) / 2

      if (arr(mid) == toFind) {
        return mid
      }

      if (arr(mid) > toFind) {
        return recursiveBinarySearch(arr, left, mid - 1, toFind)
      }

      return recursiveBinarySearch(arr, mid + 1, right, toFind)
    }

    -1
  }

  def main(args: Array[String]): Unit = {
    val arr = Array(2, 3, 6, 7, 12, 13, 17, 19, 21, 39)
    val toFind = 13

    val index = recursiveBinarySearch(arr, 0, arr.length - 1, toFind)

    if (index == -1) {
      println("not found")
    } else {
      println(s"Found at index: $index")
    }
  }
}

 
 
/*
run:
   
Found at index: 5
 
*/

 



answered Dec 13, 2024 by avibootz
...