Complete the code to perform a linear search that returns the index of the target or -1 if not found.
fn linear_search(arr: &[i32], target: i32) -> i32 {
for (index, &value) in arr.iter().enumerate() {
if value == [1] {
return index as i32;
}
}
-1
}The function compares each element value with the target. When they match, it returns the current index.
Complete the code to perform a binary search on a sorted array and return the index of the target or -1 if not found.
fn binary_search(arr: &[i32], target: i32) -> i32 {
let mut left = 0;
let mut right = arr.len() as i32 - 1;
while left <= right {
let mid = left + (right - left) / 2;
if arr[mid as usize] == [1] {
return mid;
} else if arr[mid as usize] < target {
left = mid + 1;
} else {
right = mid - 1;
}
}
-1
}The binary search compares the middle element arr[mid] with the target to decide the next search range.
Fix the error in the binary search code: complete the blank to correctly calculate the middle index without overflow.
let mid = [1] + (right - left) / 2;
Calculating mid as left + (right - left) / 2 prevents overflow compared to (left + right) / 2.
Fill both blanks to create a Rust function that measures and compares the time taken by linear and binary search.
use std::time::Instant;
fn compare_search_times(arr: &[i32], target: i32) {
let start_linear = Instant::now();
let _ = linear_search(arr, [1]);
let duration_linear = start_linear.elapsed();
let start_binary = Instant::now();
let _ = binary_search(arr, [2]);
let duration_binary = start_binary.elapsed();
println!("Linear search took: {:?}", duration_linear);
println!("Binary search took: {:?}", duration_binary);
}Both searches should look for the same target value to fairly compare their times.
Fill all three blanks to create a Rust function that generates a sorted vector, searches for a target, and prints the results.
fn main() {
let arr: Vec<i32> = (1..=10000).map(|x| x [1] 1).collect();
let target = 5000;
let index_linear = linear_search(&arr, [2]);
let index_binary = binary_search(&arr, [3]);
println!("Linear Search found target at index: {}", index_linear);
println!("Binary Search found target at index: {}", index_binary);
}The vector is generated by adding 1 to each number from 1 to 10000. Both searches look for the target value.
