Scala Program to Implement Binary Search

Scala Program to Implement Binary Search

Binary Search is a powerful searching algorithm that is much faster than Linear Search for sorted datasets. Instead of checking each element one by one, Binary Search repeatedly divides the array in half and compares the target with the middle element. If the target is smaller than the middle element, the search continues on the left half; if it is larger, the search continues on the right half. This divide-and-conquer approach makes Binary Search extremely efficient, with a time complexity of O(log n), compared to Linear Search’s O(n).

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Binary Search is widely used in programming whenever you have a sorted array or list, such as searching for a number in a phone directory or finding a value in a sorted database. Learning Binary Search in Scala helps beginners understand recursion, loops, and algorithmic efficiency. It also lays a foundation for more advanced searching techniques and problem-solving strategies.

Program 1: Iterative Binary Search

This program demonstrates Binary Search using a simple while loop to find an integer in a sorted array.

object BinarySearchIterative {

  def binarySearch(arr: Array[Int], target: Int): Int = {

    var left = 0
    var right = arr.length - 1

    while (left <= right) {

      val mid = left + (right - left) / 2

      if (arr(mid) == target) return mid
      else if (arr(mid) < target) left = mid + 1
      else right = mid - 1

    }

    -1

  }

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

    val data = Array(1, 3, 5, 7, 9, 11)
    val target = 7
    val index = binarySearch(data, target)

    if (index != -1) println(s"Element $target found at index $index")
    else println(s"Element $target not found")

  }

}

This iterative approach uses two pointers to maintain the search range and repeatedly calculates the middle index. Beginners can understand how dividing the array reduces the number of comparisons and makes the search faster than Linear Search.

Program 2: Recursive Binary Search

This version demonstrates Binary Search using recursion, which can make the code more elegant and easy to read.

object BinarySearchRecursive {

  def binarySearch(arr: Array[Int], target: Int, left: Int = 0, right: Int = -1): Int = {

    val r = if (right == -1) arr.length - 1 else right

    if (left > r) return -1

    val mid = left + (r - left) / 2

    if (arr(mid) == target) mid
    else if (arr(mid) < target) binarySearch(arr, target, mid + 1, r)
    else binarySearch(arr, target, left, mid - 1)

  }

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

    val data = Array(2, 4, 6, 8, 10)
    val target = 6
    val index = binarySearch(data, target)

    if (index != -1) println(s"Element $target found at index $index")
    else println(s"Element $target not found")

  }

}

Recursion allows the function to call itself on smaller halves of the array until the target is found. Beginners can learn how recursive thinking simplifies code and helps understand the divide-and-conquer strategy.

Program 3: Binary Search for Floating-Point Numbers

Binary Search can also be applied to arrays of floating-point numbers, as long as the array is sorted.

object BinarySearchFloat {

  def binarySearch(arr: Array[Double], target: Double): Int = {

    var left = 0
    var right = arr.length - 1

    while (left <= right) {

      val mid = left + (right - left) / 2

      if (arr(mid) == target) return mid
      else if (arr(mid) < target) left = mid + 1
      else right = mid - 1

    }

    -1

  }

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

    val data = Array(1.1, 2.3, 3.5, 4.7, 5.9)
    val target = 3.5
    val index = binarySearch(data, target)

    if (index != -1) println(s"Element $target found at index $index")
    else println(s"Element $target not found")

  }

}

Using floating-point numbers teaches beginners that Binary Search is versatile. The algorithm logic remains unchanged, highlighting that comparisons and sorted order are the only requirements.

Program 4: Binary Search for Strings

Binary Search can also be applied to sorted arrays of strings to find a target word efficiently.

object BinarySearchStrings {

  def binarySearch(arr: Array[String], target: String): Int = {

    var left = 0
    var right = arr.length - 1

    while (left <= right) {

      val mid = left + (right - left) / 2

      if (arr(mid) == target) return mid
      else if (arr(mid) < target) left = mid + 1
      else right = mid - 1

    }

    -1

  }

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

    val words = Array("apple", "banana", "cherry", "date", "grape")
    val target = "cherry"
    val index = binarySearch(words, target)

    if (index != -1) println(s"Word '$target' found at index $index")
    else println(s"Word '$target' not found")

  }

}

Sorting strings alphabetically allows Binary Search to be used on text data. Beginners can see how the comparison operators work for strings and understand the generality of the algorithm.

Program 5: Binary Search for First Occurrence

This program finds the first occurrence of a target in an array with duplicate elements.

object BinarySearchFirstOccurrence {

  def binarySearchFirst(arr: Array[Int], target: Int): Int = {

    var left = 0
    var right = arr.length - 1
    var result = -1

    while (left <= right) {

      val mid = left + (right - left) / 2

      if (arr(mid) == target) {
        result = mid
        right = mid - 1
      } else if (arr(mid) < target) left = mid + 1
      else right = mid - 1

    }

    result

  }

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

    val data = Array(1, 3, 3, 3, 5, 7)
    val target = 3
    val index = binarySearchFirst(data, target)

    if (index != -1) println(s"First occurrence of $target found at index $index")
    else println(s"Element $target not found")

  }

}

Finding the first occurrence of a duplicate element teaches beginners how to adapt Binary Search for more complex requirements. The algorithm is still efficient but requires careful handling of indices.

Frequently Asked Questions (FAQ)

This section answers common questions beginners have when learning Binary Search in Scala.

Q1: What is Binary Search?
Binary Search is an algorithm that finds a target element in a sorted array by repeatedly dividing the search range in half.

Q2: Can Binary Search be used on unsorted arrays?
No, the array must be sorted. For unsorted arrays, Linear Search is used.

Q3: Is Binary Search faster than Linear Search?
Yes, Binary Search has a time complexity of O(log n), which is much faster for large sorted datasets.

Q4: Can Binary Search work with strings or floating-point numbers?
Yes, as long as the data can be compared and is sorted.

Q5: How do I find duplicates using Binary Search?
You can modify Binary Search to continue searching on one side after finding a match to locate the first or last occurrence.

Conclusion

Binary Search is a cornerstone algorithm in programming that demonstrates the power of divide-and-conquer strategies. By splitting the search range repeatedly, it finds elements efficiently in sorted datasets.

Through multiple examples in Scala—including iterative and recursive methods, integers, floating-point numbers, strings, and duplicates—beginners can see how Binary Search adapts to different scenarios. Practicing these programs reinforces the understanding of loops, recursion, and algorithmic efficiency, making it an essential skill for every programmer.

Scroll to Top