I was curious about how much difference occured when if I implement a code to find max elelment of a vector and I've used two functions: one of them uses divide and conquer algorithm and other uses normal recursion. At the first glance, I thought that divide and conquer algorithm is less efficient than other because it generates temporary variables, it has more comparisons than other and more. However, when I test both of them results are completely different from my ideas. The codes and results are below:
// Divide and conquer
#include <bits/stdc++.h>
#define maxi 100000
long int c = 0; // counter for number of function cals
using namespace std;
using namespace std::chrono;
int find_max (vector<int> &a, int l, int r){
++c;
if (l == r){
return a[l];
}
int m = (l+r)/2;
int u = find_max(a,l,m);
int v = find_max(a,m+1,r);
if(u > v)
return u;
else
return v;
}
int main(){
srand(time(NULL));
vector<int> a;
for (int i = 0; i < maxi; ++i){
int b = rand() % maxi + 1;
a.push_back(b);
}
auto start = high_resolution_clock::now();
cout << find_max(a, 0, maxi-1) << endl;
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: " << duration.count() << " microseconds" << endl;
cout << "counter: " << c << endl;
}
Results of divide and conquer algorithm
// Linear recursion
#include <bits/stdc++.h>
#define maxi 100000
long int c = 0;
using namespace std;
using namespace std::chrono;
int find_max (vector<int> &a, int i){
++c;
if (i == 1){
return a[0];
}
return max(a[i-1], find_max(a, i-1));
}
int main(){
srand(time(NULL));
vector<int> a;
for (int i = 0; i < maxi; ++i){
int b = rand() % maxi + 1;
a.push_back(b);
}
auto start = high_resolution_clock::now();
cout << find_max(a, a.size()) << endl;
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << "Time taken by function: " << duration.count() << " microseconds" << endl;
cout << "counter: " << c << endl;
}
Results of linear recursion algorithm
What is the reason of this difference, what do you think? Thanks in advance.