Home »
Rust »
Rust Programs
Rust program to search an item into the array using binary search
Rust | Array Example: Write a program to search an item into the array using binary search.
Submitted by Nidhi, on October 21, 2021
Problem Solution:
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 binary search technique.
Note: Binary search is used to search an item into a sorted array.
Program/Source Code:
The source code to search an item into the array using binary search is given below. The given program is compiled and executed successfully.
// Rust program to search an item into
// the array using binary search
use std::io;
fn main()
{
let mut arr:[i32;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:i32 = 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) / 2;
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) / 2;
}
if flag ==0 {
println!("Item {0} not found in array",item);
}
}
Output:
Enter Item:
23
Item 23 found at index 3
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 binary search technique and print the index of the item into the array on the console screen.
Rust Arrays Programs »