×

Ruby Tutorial

Ruby Basics

Ruby Control Statements

Ruby Methods

Ruby Classes and Methods

Ruby Arrays

Ruby Sets

Ruby Strings

Ruby Classes & Objects

Ruby Hash

Ruby Tools

Ruby Functions

Ruby Built-in Functions

Misc.

Ruby Programs

Ruby program to search an item into the array using interpolation search

Last Updated : December 15, 2025

Problem Solution

In this program, we will create an array of integer elements. Then we will read an item from the user to search into the array using interpolation search and print the index of the item in the array.

The interpolation search is an improved version of binary search. Here we will use the improved formula to calculate the middle element.

Program/Source Code

The source code to search an item into the array using interpolation search is given below. The given program is compiled and executed successfully.

# Ruby program to search an item into the array 
# using interpolation search

arr = [12,23,39,57,68];

item =   0;
flag =   -1;

first = 0;
last = arr.size() - 1;
middle = first + (((last - first) / (arr[last] - arr[first])) * (item - arr[first]))

print "Enter item: ";
item = gets.chomp.to_i;  

while(first<=last)
    if(arr[middle]<item)
        first=middle + 1;
    elsif(arr[middle]==item)
        flag=middle;
        break;
    else
        last = middle - 1;
    end
    middle = first + (((last - first) / (arr[last] - arr[first])) * (item - arr[first]));
end

if(flag>=0)
    print "Item found at index: ",flag,"\n"; 
else
    print "Item not found\n"; 
end

Output

Enter item: 39
Item found at index: 2

Explanation

In the above program, we created an array of integer elements. Then we read an item from the user to search into the sorted array using an interpolation search mechanism. After that, we printed the index of the item in the array, if the item was found. Otherwise, we printed the "Item not found" message.

Ruby Arrays Programs »


Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.