算法导论(第三版)参考答案:练习4.1-1,练习4.1-2,练习4.1-3,练习4.1-4,练习4.1-5
Exercise 4.1-1
What does FIND-MAXIMUM-SUBARRAY return when all elements of A are negative?
返回
Exercise 4.1-2
Write pseudocode for the brute-force method of solving the maximum-subarray problem. Your procedure should run in Θ(n2) time.
FIND-MAX-SUBARRAY(A, low, high)
left = 0
right = 0
sum = -∞
for i = low to high
current-sum = 0
for j = i to high
current-sum += A[j]
if sum < current-sum
sum = current-sum
left = i
right = j
return (left, right, sum)
Exercise 4.1-3
Implement both the brute-force and recursive algorithms for the maximum-subarray problem on your own computer. What problem size n0 gives the crossover point at which the recursive algorithm beats the brute-force algorithm? Then, change the base case of the recursive algorithm to use the brute-force algorithm whenever the problem size is less than n0 . Does that change the crossover point?
C code
#include <limits.h>
#define CROSSOVER_POINT 37
// A struct to represent the tuple
typedef struct {
unsigned left;
unsigned right;
int sum;
} max_subarray;
// The brute force approach
max_subarray find_maximum_subarray_brute(int A[], unsigned low, unsigned high) {
max_su