Q:

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

belongs to collection: Rust Arrays Programs

0

In this program, we will create an array of integer elements then we will read an item from the user and search the item into the array using the interpolation search technique.

Note: Interpolation search is used to search an item into a sorted array.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

// Rust program to search an item into array 
// using interpolation search

use std::io;

fn main() 
{
	let mut arr:[usize;5] = [1,5,11,23,26];
	let mut flag:usize   = 0;

	let mut first:usize  = 0;
	let mut last:usize   = 0;
	let mut middle:usize = 0;

	let mut item:usize = 0;
	let mut input = String::new();

	println!("Enter Item: ");
	io::stdin().read_line(&mut input).expect("Not a valid string");
	item = input.trim().parse().expect("Not a valid number");

	first = 0;
	last = 4;

	middle = first + (((last - first) / (arr[last] - arr[first])) * (item - arr[first]));

	while first<=last
	{
		if arr[middle] < item {
			first = middle + 1;
		} 
		else if arr[middle] == item {
			flag=1;
			println!("Item {0} found at index {1}", item, middle);
			break;
		} 
		else {
			last = middle - 1;
		}
		middle = first + (((last - first) / (arr[last] - arr[first])) * (item - arr[first]));
	}

	if flag ==0 {
		println!("Item {0} not found in array",item);
	} 
}

Output:

Enter Item: 
11
Item 11 found at index 2

Explanation:

Here, we created an array of the integer with 5 elements, and then we read the item from the user.

After that, we searched the item into the array using the interpolation search technique and print the index of the item into the array.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust Arrays Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Rust program to sort an array in ascending order u... >>
<< Rust program to search an item into the array usin...