数组区段的最大最小值
题干
本题要求实现一个函数,找出数组中一部分数据的最大值和最小值。
题目保证没有无效数据。
函数接口定义:
void sublistMaxMin ( int* from, int* to, int* max, int* min );
其中 from和to都是用户传入的参数,分别存放数组部分数据的起始地址和结束地址,并且from<=to。
其中max和min为用户传入的地址,分别用于在sublistMaxMin中保存from至to对应区段中数组元素的最大值和最小值的地址。
裁判测试程序样例:
#include <stdio.h>
void sublistMaxMin ( int* from, int* to, int* max, int* min );
int main()
{
int list[1000];
int len=0;
int from, to, max, min;
scanf("%d", &len);
int i;
for(i=0; i<len; i++){
scanf("%d", &list[i]);
}
scanf("%d%d", &from, &to);
sublistMaxMin(list+from, list+to, &max, &min);
printf("list[%d-%d]: max = %d, min = %d\n", from, to, max, min);
return 0;
}
/* 请在这里填写答案 */
输入样例:
5
1 2 3 4 5
0 4
输出样例:
list[0-4]: max = 5, min = 1
解答过程
void sublistMaxMin(int* from, int* to, int* max, int* min) {
*max = *from;
*min = *from;
for (int* ptr = from + 1; ptr <= to; ptr++) {
if (*ptr > *max) {
*max = *ptr;
}
if (*ptr < *min) {
*min = *ptr;
}
}
}