用三分法求给定数组的最大值、最小值、数组的和的代码
时间: 2023-03-27 08:04:51 浏览: 94
以下是用三分法求给定数组的最大值、最小值、数组的和的代码:
```
#include <stdio.h>
int main() {
int n;
scanf("%d", &n);
int a[n];
for (int i = ; i < n; i++) {
scanf("%d", &a[i]);
}
int l = , r = n - 1;
int max_val = a[], min_val = a[], sum = ;
while (l <= r) {
int mid = (l + r) / 2;
if (a[mid] > max_val) {
max_val = a[mid];
}
if (a[mid] < min_val) {
min_val = a[mid];
}
sum += a[mid];
if (mid > l) {
if (a[mid - 1] > a[mid]) {
r = mid - 1;
} else {
l = mid + 1;
}
} else {
break;
}
if (mid < r) {
if (a[mid + 1] > a[mid]) {
l = mid + 1;
} else {
r = mid - 1;
}
} else {
break;
}
}
printf("最大值:%d\n", max_val);
printf("最小值:%d\n", min_val);
printf("数组的和:%d\n", sum);
return ;
}
```
阅读全文