C语言-递归法寻找数组中最小值
int getMin(int array[], int n) {
int val1, val2, val3;
if (n == 1)
return array[0];
if (n % 2 == 0) {
val1 = getMin(array, n / 2);
val2 = getMin(array + n / 2, n / 2);
if (val1 < val2)
return val1;
else
return val2;
}
if (n % 2 != 0) {
val1 = getMin(array, n / 2);
val2 = getMin(array + n / 2 + 1, n / 2);
val3 = array[n / 2];
if (val1 < val2) {
if (val1 < val3)
return val1;
else
return val3;
} else {
if (val2 < val3)
return val2;
else
return val3;
}
}
return 0;
}
int main(int argc, const char *argv[]) {
int array[10] = {11, 13, 23, 44, 4, 43, 11, 23, 111, -1}, val;
val = getMin(array, sizeof(array) / sizeof(int));
printf("The minum element of the array is %d \n", val);
return 0;
}
结果:
还没有评论,来说两句吧...