Question: Write recursive and iterative functions to compare by execution time. #include //needed to perform C++I/O #include #include //use clock_t start, stop; using namespace std; int
Write recursive and iterative functions to compare by execution time.
#include
int rabbit(int n); int IterativeRabbit(int n); void writeBackward(string s); void InterativewriteBackward(string s);
int binarySearch(const int anArray[], int first, int last, int target); int IterativeBinarySearch(int arr[], int size, int x) { int l = 0, r = size - 1; while (l <= r) { int m = l + (r - l) / 2;
if (arr[m] == x) return m;
if (arr[m] < x) l = m + 1;
else r = m - 1; } return -1;
} const int SIZE = 40, SIZE2 = 100000;
int rabbit(int n) { if (n == 1 || n == 2) return 1; return rabbit(n - 1) + rabbit(n - 2); } int InterativeRabbit(int n) { int a[n + 1]; a[1] = 1; a[2] = 1; for (int i = 3; i <= n; i++) a[i] = a[i - 1] + a[i - 2]; return a[n]; } void writeBackward(string s) { if (s.length() > 0) { cout << s[s.length() - 1]; writeBackward(s.substr(0, s.length() - 1)); } } int binarySearch(const int anArray[], int first, int last, int target) { if (last >= first) { int mid = first + (last - first) / 2; if (anArray[mid] == target) return mid; if (anArray[mid] > target) return binarySearch(anArray, first, mid - 1, target); return binarySearch(anArray, mid + 1, last, target); } return -1; } int main() { cout << "Part 1 ************** ";
int res, array[SIZE2] = {};
//for binary search tree for (int i = 0; i < SIZE2; i++) { array[i] = 2 * i + 1; }
string s = "recursive function calls by itself ";
clock_t start, stop;
//rabbit functions start = clock(); res = rabbit(SIZE); stop = clock(); cout << "The return value of the rabbit function is " << res << endl; cout << "Running time for the function is " << static_cast
return 0; }
On line 41 I get an error saying " the value of parameter 'n' cannot be used as a constant."
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
