Scala Program to Implement Interpolation Search

Scala Program to Implement Interpolation Search

Interpolation Search is a smart searching algorithm that improves upon Binary Search for uniformly distributed, sorted datasets. Unlike Binary Search, which always checks the middle element, Interpolation Search estimates the position of the target using the values at the low and high ends of the array. This can make the search faster for large datasets where elements are evenly spaced, because it “guesses” a more likely position instead of blindly splitting in the middle.

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

Interpolation Search is widely used in applications where quick lookups in numeric, sorted arrays are needed. It can be applied in searching databases, stock prices, or any scenario where the data is predictable and distributed uniformly. Learning Interpolation Search in Scala helps beginners understand advanced searching techniques, interpolation formulas, and how to combine loops, conditionals, and recursion effectively.

Program 1: Iterative Interpolation Search

This program demonstrates the basic iterative Interpolation Search on a sorted array of integers.

object InterpolationSearchIterative {

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

    var low = 0
    var high = arr.length - 1

    while (low <= high && target >= arr(low) && target <= arr(high)) {

      val pos = low + ((target - arr(low)) * (high - low) / (arr(high) - arr(low)))

      if (arr(pos) == target) return pos
      else if (arr(pos) < target) low = pos + 1
      else high = pos - 1

    }

    -1

  }

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

    val data = Array(10, 20, 30, 40, 50, 60)
    val target = 40
    val index = interpolationSearch(data, target)

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

  }

}

This program uses the interpolation formula to estimate the likely position of the target. Beginners can see how the formula improves search efficiency by narrowing the range faster than Binary Search in uniform datasets.

Program 2: Recursive Interpolation Search

This example shows how Interpolation Search can be implemented recursively for clarity and elegance.

object InterpolationSearchRecursive {

  def interpolationSearch(arr: Array[Int], target: Int, low: Int = 0, high: Int = -1): Int = {

    val h = if (high == -1) arr.length - 1 else high

    if (low > h || target < arr(low) || target > arr(h)) return -1
    val pos = low + ((target - arr(low)) * (h - low) / (arr(h) - arr(low)))
    if (arr(pos) == target) pos
    else if (arr(pos) < target) interpolationSearch(arr, target, pos + 1, h)
    else interpolationSearch(arr, target, low, pos - 1)

  }

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

    val data = Array(5, 15, 25, 35, 45, 55)
    val target = 25
    val index = interpolationSearch(data, target)

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

  }

}

Recursion makes the code neat and allows beginners to see how the search range is divided and adjusted each step. It demonstrates the divide-and-conquer approach with estimation instead of middle splitting.

Program 3: Interpolation Search for Floating-Point Numbers

Interpolation Search can also handle floating-point numbers in a sorted, uniform array.

object InterpolationSearchFloat {

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

    var low = 0
    var high = arr.length - 1

    while (low <= high && target >= arr(low) && target <= arr(high)) {

      val pos = low + ((target - arr(low)) * (high - low) / (arr(high) - arr(low))).toInt

      if (arr(pos) == target) return pos
      else if (arr(pos) < target) low = pos + 1
      else high = pos - 1

    }

    -1

  }

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

    val data = Array(1.0, 2.5, 4.0, 5.5, 7.0)
    val target = 4.0
    val index = interpolationSearch(data, target)

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

  }

}

This program helps beginners understand that Interpolation Search works not only with integers but also with floating-point numbers. The concept remains the same, while the formula handles real values.

Program 4: Interpolation Search for Strings (Numeric Strings)

Although Interpolation Search works best with numeric data, it can handle strings that can be mapped to numeric values.

object InterpolationSearchString {

  def stringToInt(s: String): Int = s.toInt

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

    var low = 0
    var high = arr.length - 1
    val t = stringToInt(target)

    while (low <= high && t >= stringToInt(arr(low)) && t <= stringToInt(arr(high))) {

      val pos = low + ((t - stringToInt(arr(low))) * (high - low) / 
                      (stringToInt(arr(high)) - stringToInt(arr(low))))

      if (stringToInt(arr(pos)) == t) return pos
      else if (stringToInt(arr(pos)) < t) low = pos + 1
      else high = pos - 1

    }

    -1

  }

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

    val data = Array("10", "20", "30", "40", "50")
    val target = "30"
    val index = interpolationSearch(data, target)

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

  }

}

This program teaches beginners that Interpolation Search is flexible and can work with data that can be converted to numeric values, demonstrating practical problem-solving.

Program 5: Interpolation Search with Multiple Occurrences

This program finds all occurrences of a target in a sorted array with repeated elements.

object InterpolationSearchMultiple {

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

    var low = 0
    var high = arr.length - 1
    val indices = scala.collection.mutable.ArrayBuffer[Int]()

    while (low <= high && target >= arr(low) && target <= arr(high)) {

      val pos = low + ((target - arr(low)) * (high - low) / (arr(high) - arr(low)))

      if (arr(pos) == target) {

        indices += pos
        // check neighbors
        var left = pos - 1

        while (left >= 0 && arr(left) == target) { indices += left; left -= 1 }

        var right = pos + 1

        while (right < arr.length && arr(right) == target) { indices += right; right += 1 }

        return indices.sorted.toArray

      } else if (arr(pos) < target) low = pos + 1
      else high = pos - 1

    }

    indices.toArray

  }

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

    val data = Array(10, 20, 20, 20, 30, 40)
    val target = 20
    val indices = interpolationSearchAll(data, target)

    if (indices.nonEmpty) println(s"Element $target found at indices: ${indices.mkString(", ")}")
    else println(s"Element $target not found")

  }

}

By collecting all matching indices, this program shows a more advanced usage of Interpolation Search. Beginners can learn how to handle repeated values while keeping the search efficient.

Frequently Asked Questions (FAQ)

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

Q1: What is Interpolation Search?
Interpolation Search estimates the position of the target based on the values at the low and high ends of a sorted array.

Q2: Is Interpolation Search faster than Binary Search?
Yes, for uniformly distributed datasets, it can be faster than Binary Search because it “guesses” a closer position.

Q3: Can Interpolation Search handle floating-point numbers?
Yes, as long as the array is sorted and uniformly distributed.

Q4: Can Interpolation Search work with strings?
It works with strings that can be converted to numeric values. For general strings, Linear or Binary Search is better.

Q5: When should I use Interpolation Search?
It is ideal for large, sorted datasets with uniform distribution where quick lookups are needed.

Conclusion

Interpolation Search is a powerful searching algorithm that improves efficiency over Binary Search for the right datasets. By learning the iterative and recursive approaches in Scala, as well as applications for integers, floating-point numbers, strings, and repeated elements, beginners can understand how estimation speeds up searching. Practicing these programs in Scala builds confidence in algorithmic thinking, making it easier to explore more advanced searching and optimization techniques in programming.

Scroll to Top