F# Program to Implement Interpolation Search

F# Program to Implement Interpolation Search

Searching efficiently in a dataset is one of the core skills for any programmer. While Binary Search divides the array into halves regardless of the value, Interpolation Search improves on this by estimating where the key might be based on its value relative to the lowest and highest elements in the array. This can make searching faster for uniformly distributed data, such as phone numbers, student IDs, or product codes.

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 especially useful when the data is sorted and values are spread evenly. By “guessing” the probable position of the key rather than always choosing the middle, this algorithm can reduce the number of comparisons needed. For beginners, learning Interpolation Search introduces the idea of value-based search, which combines logic, arithmetic, and recursion to achieve better performance in certain scenarios.

Program 1: Interpolation Search Using a Loop

This program demonstrates Interpolation Search using a while-loop, which repeatedly estimates the position of the key in a sorted array and narrows down the search range accordingly.

open System

let interpolationSearch (arr : int[]) key =

    let mutable low = 0
    let mutable high = arr.Length - 1
    let mutable foundIndex = -1

    while low <= high && key >= arr.[low] && key <= arr.[high] && foundIndex = -1 do

        if arr.[high] = arr.[low] then
            if arr.[low] = key then foundIndex <- low
        else

            let pos = low + ((key - arr.[low]) * (high - low)) / (arr.[high] - arr.[low])

            if arr.[pos] = key then
                foundIndex <- pos
            elif arr.[pos] < key then
                low <- pos + 1
            else
                high <- pos - 1

    foundIndex


[<EntryPoint>]
let main argv =

    let numbers = [| 10; 20; 30; 40; 50; 60 |]
    let key = 40
    let result = interpolationSearch numbers key

    if result <> -1 then
        printfn "Element %d found at index %d" key result
    else
        printfn "Element %d not found" key

    0

This program calculates the probable position using a simple formula based on the difference between the key and the lowest element relative to the total range. Beginners can see how Interpolation Search “guesses” the likely index rather than always taking the middle.

Program 2: Recursive Interpolation Search

Recursion is a natural fit for Interpolation Search. This program demonstrates a recursive implementation, where the search range is reduced based on the estimated position.

open System

let rec interpolationSearchRec (arr:int[]) key low high =

    if low > high || key < arr.[low] || key > arr.[high] then -1
    else

        if arr.[high] = arr.[low] then
            if arr.[low] = key then low else -1
        else
            let pos = low + ((key - arr.[low]) * (high - low)) / (arr.[high] - arr.[low])
            if arr.[pos] = key then pos
            elif arr.[pos] < key then interpolationSearchRec arr key (pos + 1) high
            else interpolationSearchRec arr key low (pos - 1)


[<EntryPoint>]
let main argv =

    let numbers = [| 5; 15; 25; 35; 45; 55 |]
    let key = 25
    let result = interpolationSearchRec numbers key 0 (numbers.Length - 1)

    if result <> -1 then
        printfn "Element %d found at index %d" key result
    else
        printfn "Element %d not found" key

    0

The recursive approach breaks the problem into smaller parts, letting beginners understand how the search focuses on the estimated section of the array until it finds the key or determines it’s absent.

Program 3: Interpolation Search for Negative and Positive Numbers

This program shows how Interpolation Search works for arrays containing both negative and positive numbers, as long as they are sorted.

open System

let rec interpolationSearchMixed (arr:int[]) key low high =

    if low > high || key < arr.[low] || key > arr.[high] then -1
    else

        if arr.[high] = arr.[low] then
            if arr.[low] = key then low else -1
        else
            let pos = low + ((key - arr.[low]) * (high - low)) / (arr.[high] - arr.[low])
            if arr.[pos] = key then pos
            elif arr.[pos] < key then interpolationSearchMixed arr key (pos + 1) high
            else interpolationSearchMixed arr key low (pos - 1)


[<EntryPoint>]
let main argv =

    let numbers = [| -20; -10; 0; 10; 20; 30 |]
    let key = -10
    let result = interpolationSearchMixed numbers key 0 (numbers.Length - 1)

    if result <> -1 then
        printfn "Element %d found at index %d" key result
    else
        printfn "Element %d not found" key

    0

This demonstrates that the algorithm can handle negative values without any changes to the logic, as long as the array is sorted. Beginners can practice using different ranges of numbers.

Program 4: Interpolation Search Returning Option Type

Using F#’s option type makes the result safer and more idiomatic than returning -1. This version returns Some index if found, or None if not.

open System

let rec interpolationSearchOption (arr:int[]) key low high =

    if low > high || key < arr.[low] || key > arr.[high] then None
    else

        if arr.[high] = arr.[low] then
            if arr.[low] = key then Some low else None
        else

            let pos = low + ((key - arr.[low]) * (high - low)) / (arr.[high] - arr.[low])

            if arr.[pos] = key then Some pos
            elif arr.[pos] < key then interpolationSearchOption arr key (pos + 1) high
            else interpolationSearchOption arr key low (pos - 1)


[<EntryPoint>]
let main argv =

    let numbers = [| 1; 3; 5; 7; 9; 11 |]
    let key = 5

    match interpolationSearchOption numbers key 0 (numbers.Length - 1) with
    | Some index -> printfn "Element %d found at index %d" key index
    | None -> printfn "Element %d not found" key

    0

This approach teaches beginners to work with safe results and is more aligned with functional programming principles in F#.

Program 5: Step-by-Step Interpolation Search

This program prints each estimated position during the search, helping beginners visualize how the algorithm narrows down the range.

open System

let interpolationSearchStep (arr : int[]) key =

    let mutable low = 0
    let mutable high = arr.Length - 1
    let mutable foundIndex = -1

    // Loop stops if foundIndex != -1
    while low <= high && key >= arr.[low] && key <= arr.[high] && foundIndex = -1 do

        if arr.[high] = arr.[low] then

            if arr.[low] = key then
                foundIndex <- low

        else

            let pos = low + ((key - arr.[low]) * (high - low)) / (arr.[high] - arr.[low])
            printfn "Checking position %d" pos

            if arr.[pos] = key then
                foundIndex <- pos
            elif arr.[pos] < key then
                low <- pos + 1
            else
                high <- pos - 1

    foundIndex


[<EntryPoint>]
let main argv =

    let numbers = [| 10; 20; 30; 40; 50; 60 |]
    let key = 50
    let result = interpolationSearchStep numbers key

    if result <> -1 then
        printfn "Element %d found at index %d" key result
    else
        printfn "Element %d not found" key

    0

Printing the positions at each step helps beginners understand the value-based estimation that makes Interpolation Search faster for uniform distributions.

Frequently Asked Questions (FAQ)

This section answers common beginner questions about Interpolation Search.

Q1. What is Interpolation Search?
Interpolation Search is an algorithm that estimates the probable position of a key in a sorted array based on its value relative to the lowest and highest elements.

Q2. Does the array need to be sorted?
Yes, the array must be sorted, otherwise the estimation will fail, and the search may produce incorrect results.

Q3. When is Interpolation Search faster than Binary Search?
Interpolation Search is faster when the data is uniformly distributed because it can directly jump close to the key instead of always going to the middle.

Q4. Can it handle negative numbers?
Yes, negative, zero, and positive numbers can all be handled as long as the array is sorted.

Q5. Should beginners learn Interpolation Search?
Yes, it teaches value-based searching, arithmetic reasoning, and how to optimize search algorithms beyond simple methods like Binary or Linear Search.

Conclusion

Interpolation Search is an advanced search technique that builds on the idea of Binary Search but uses value estimation to jump closer to the target element. Through multiple F# programs, we explored iterative and recursive versions, handling negative numbers, using option types, and visualizing each search step.

For beginners, practicing Interpolation Search strengthens understanding of sorted data, efficient searching, and how algorithmic logic can adapt to different data distributions. By experimenting with different arrays, beginners can see firsthand the power of value-based estimation in improving search efficiency.

Scroll to Top