#include <stdio.h> #include <malloc.h> #include <time.h> int recursive(unsigned int num, int data[]) { int nextdata, curdata = *data; if (num == 1) { return curdata; } nextdata = recursive(--num, ++data); return curdata > nextdata ? curdata : nextdata; } int non_recursive(unsigned int num, int data[]) { int *stack = new int[100]; int *top = stack - 1; int nextdata, curdata = *data; //将参数存入堆栈中 for (int i = 0; i < num; i++) { top += 1; *top = num - i; top += 1; *top = *(data + i); } if (top == stack) { delete[] stack; return *top; } else { while (1) { nextdata = *top; top -= 1; if (*top == num) { delete[] stack; return curdata > nextdata ? curdata : nextdata; } else { top -= 1; curdata = curdata > nextdata ? curdata : nextdata; } } } } int simple_non_recursive(unsigned int num, int data[]) { int nextdata, curdata = *data; for (int i = 0; i < num; i++) { nextdata = data[i]; curdata = curdata > nextdata ? curdata : nextdata; } return curdata; } int main() { int maxdata, num, idx, *data; printf("Input count of integer data: "); scanf("%d", &num); if (num <= 0) { printf("count of integer data must be a positive integer !/n"); return 1; } data = (int*)malloc(num*sizeof(int)); if (NULL == data) { printf("init array failed !/n"); return 1; } printf("Now input %d integers:/n", num); for(idx = 0; idx < num; idx++) { scanf("%d", data+idx); } clock_t start_time = clock(); maxdata = recursive(num, data); clock_t finish_time = clock(); double duration = (double)(finish_time - start_time) / CLOCKS_PER_SEC; printf("Input success. Maximum integer = %d, Using time = %fs/n", maxdata, duration); start_time = clock(); maxdata = non_recursive(num, data); finish_time = clock(); duration = (double)(finish_time - start_time) / CLOCKS_PER_SEC; printf("Input success. Maximum integer = %d, Using time = %fs/n", maxdata, duration); start_time = clock(); maxdata = simple_non_recursive(num, data); finish_time = clock(); duration = (double)(finish_time - start_time) / CLOCKS_PER_SEC; printf("Input success. Maximum integer = %d, Using time = %fs/n", maxdata, duration); free(data); return 0; }