Which of the following best explains the main advantage of using the divide and conquer approach in algorithms?
Think about how breaking a big task into smaller tasks can help solve it faster.
Divide and conquer splits a problem into smaller subproblems, solves each one, and then combines the answers. This often reduces the time needed compared to solving the whole problem at once.
What is the output of this Rust code that uses divide and conquer to sum elements?
fn sum_slice(arr: &[i32]) -> i32 {
if arr.len() == 1 {
arr[0]
} else {
let mid = arr.len() / 2;
sum_slice(&arr[..mid]) + sum_slice(&arr[mid..])
}
}
fn main() {
let numbers = [2, 4, 6, 8];
let result = sum_slice(&numbers);
println!("{}", result);
}Sum all numbers: 2 + 4 + 6 + 8.
The function splits the array into halves recursively and sums all elements. The total sum is 2 + 4 + 6 + 8 = 20.
What error will this Rust code produce when run?
fn max_slice(arr: &[i32]) -> i32 {
if arr.len() == 1 {
arr[0]
} else {
let mid = arr.len() / 2;
let left_max = max_slice(&arr[..mid]);
let right_max = max_slice(&arr[mid..]);
if left_max > right_max {
left_max
} else {
right_max
}
}
}
fn main() {
let empty: [i32; 0] = [];
let result = max_slice(&empty);
println!("{}", result);
}What happens if the input slice is empty?
The function lacks a base case for empty slices. It recurses infinitely by repeatedly calling itself on empty slices, causing a stack overflow.
What is the printed output of this Rust code that merges two sorted slices?
fn merge(left: &[i32], right: &[i32]) -> Vec<i32> {
let mut result = Vec::new();
let mut i = 0;
let mut j = 0;
while i < left.len() && j < right.len() {
if left[i] < right[j] {
result.push(left[i]);
i += 1;
} else {
result.push(right[j]);
j += 1;
}
}
while i < left.len() {
result.push(left[i]);
i += 1;
}
while j < right.len() {
result.push(right[j]);
j += 1;
}
result
}
fn main() {
let left = [1, 4, 7];
let right = [2, 3, 6, 8];
let merged = merge(&left, &right);
println!("{:?}", merged);
}Merge two sorted lists by picking the smallest element each time.
The merge function combines two sorted slices into one sorted vector by comparing elements one by one.
Which statement best explains how divide and conquer improves the efficiency of algorithms like merge sort?
Think about how splitting the problem repeatedly affects the total work done.
Divide and conquer splits the problem into halves repeatedly (log n times), and each level does linear work merging results, leading to O(n log n) time complexity.
