C语言编程--递归程序--求数组的最大元素值
任务:Finding the maximum among N N N items stored in an array a [ 0 ] a[0] a[0], … \ldots …, a [ N − 1 ] a[N - 1] a[N−1].
实现:
#include <stdio.h>
typedef char Item;Item max(Item a[], int l, int r);Item max2(Item a[], int N);int main(int argc, char** argv){
Item a[] = {'T', 'I', 'N', 'Y', 'E', 'X', 'A', 'M', 'P', 'L', 'E'};Item maxNum = max2(a, 11);printf("%c\n", maxNum);return 0;
}/*** Program 5.6 Divide-and-conquer to find the maximum* -------------------------------------------------------------------------------------------------* This function divides a file a[l],. . . , a[r] into a[l],. . . , a[m] and a[m+1],. . . , a[r],* finds the maximum elements in the two parts (recursively), and * returns the larger of the two as the maximum element in the whole file. * It assumes that Item is a first-class type for which > is defined.* If the file size is even, the two parts are equal in size; * if the file size is odd, the size of the first part is 1 greater than the size of the second part.*/
Item max(Item a[], int l, int r){if (l == r) {return a[l];}Item u, v;int m = (l+r)/2;u = max(a, l, m);v = max(a, m+1, r);if (u > v) {return u;}else {return v;}}Item max2(Item a[], int N){// Item t = a[0];// int i;// for (i = 1; i < N; i++) {// if (a[i] > t) {// t = a[i];// }// }// return t;return max(a, 0, N-1);
}
示例程序5.6的递归分析示意图
递归调用树结构表示
- 后续遍历就是调用顺序加返回顺序
C语言编程环境支持示例递归计算的内部栈内容