Which of the following best explains the main advantage of 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 independently, and then combines the results. This often leads to faster and more efficient algorithms.
What is the printed output of the following JavaScript code that uses divide and conquer to sort an array?
function merge(left, right) {
let result = [];
while (left.length && right.length) {
if (left[0] < right[0]) result.push(left.shift());
else result.push(right.shift());
}
return result.concat(left).concat(right);
}
function mergeSort(arr) {
if (arr.length <= 1) return arr;
const mid = Math.floor(arr.length / 2);
const left = mergeSort(arr.slice(0, mid));
const right = mergeSort(arr.slice(mid));
return merge(left, right);
}
const array = [5, 3, 8, 4, 2];
console.log(mergeSort(array));Merge sort sorts the array in ascending order by dividing and merging.
The mergeSort function divides the array until single elements remain, then merges them back in sorted order, resulting in a sorted array.
What will be the output of the following JavaScript code that uses divide and conquer to find a number in a sorted array?
function binarySearch(arr, target, left = 0, right = arr.length - 1) { if (left > right) return -1; const mid = Math.floor((left + right) / 2); if (arr[mid] === target) return mid; else if (arr[mid] < target) return binarySearch(arr, target, mid + 1, right); else return binarySearch(arr, target, left, mid - 1); } const sortedArray = [1, 3, 5, 7, 9, 11]; console.log(binarySearch(sortedArray, 7));
Remember array indexes start at 0.
The number 7 is at index 3 in the array. The binary search returns this index after dividing the search space.
Which of the following is NOT a typical benefit of using divide and conquer algorithms?
Think about how divide and conquer affects time complexity.
Divide and conquer improves efficiency but does not guarantee constant time execution. The time depends on the problem and how it is divided.
Consider the problem of counting how many pairs (i, j) in an array satisfy i < j and arr[i] > arr[j]. This is called counting inversions.
Which divide and conquer approach below correctly counts inversions while sorting the array?
Think about how merge sort merges two sorted halves and how that can help count inversions efficiently.
During merge sort, when merging two sorted halves, counting how many elements from the right half come before elements from the left half gives the number of inversions efficiently.
