Complete the code to perform a comparison-based sort using Rust's built-in method.
let mut numbers = vec![5, 3, 8, 1]; numbers.[1](); println!("{:?}", numbers);
reverse instead of sort.push or pop which modify the vector size.The sort method sorts the vector in ascending order using comparison-based sorting.
Complete the code to perform a non-comparison based sort using counting sort logic for small integers.
fn counting_sort(arr: &mut [usize], max_val: usize) {
let mut count = vec![0; max_val + 1];
for &num in arr.iter() {
count[[1]] += 1;
}
let mut idx = 0;
for num in 0..=max_val {
for _ in 0..count[num] {
arr[idx] = num;
idx += 1;
}
}
}
let mut data = vec![2, 5, 3, 0, 2, 3, 0, 3];
counting_sort(&mut data, 5);
println!("{:?}", data);idx instead of num as index.arr[num] which is incorrect syntax here.We increment the count for the current number num in the array to track its frequency.
Fix the error in the code to correctly implement radix sort for sorting non-negative integers.
fn counting_sort_for_radix(arr: &mut [u32], exp: u32) {
let mut output = vec![0; arr.len()];
let mut count = vec![0; 10];
for &num in arr.iter() {
count[((num / [1]) % 10) as usize] += 1;
}
for i in 1..10 {
count[i] += count[i - 1];
}
for &num in arr.iter().rev() {
let index = ((num / (exp)) % 10) as usize;
output[count[index] - 1] = num;
count[index] -= 1;
}
for i in 0..arr.len() {
arr[i] = output[i];
}
}
let mut data = vec![170, 45, 75, 90, 802, 24, 2, 66];
counting_sort_for_radix(&mut data, 10);
println!("{:?}", data);exp.The variable exp represents the current digit place (1, 10, 100, etc.) used in radix sort.
Fill both blanks to create a dictionary comprehension that filters and transforms a list of numbers to their squares if they are even.
let numbers = vec![1, 2, 3, 4, 5]; let squares: std::collections::HashMap<_, _> = numbers.iter() .filter(|&&x| x [1] 2 == 0) .map(|&x| (x, x [2] x)) .collect(); println!("{:?}", squares);
The modulo operator % checks if a number is even, and the multiplication operator * calculates the square.
Fill all three blanks to create a HashMap comprehension that stores uppercase keys and their values only if the value is positive.
let data = std::collections::HashMap::from([ ("apple", 3), ("banana", -1), ("cherry", 5), ]); let filtered: std::collections::HashMap<_, _> = data.iter() .filter(|&(_, &v)| v [1] 0) .map(|(&k, &v)| (k.[2](), v)) .collect(); println!("{:?}", filtered);
len instead of to_uppercase.We filter values greater than zero using >, convert keys to uppercase with to_uppercase(), and collect the filtered pairs.
