I have following code I was told findmin
is O(n^2), but I cannot see it.
#include <iostream>
#include <cstdlib>
#include <ctime>
int findmin(const int a[], int n);
int cnt = 0;
int main (void)
{
int num = 100;
std::srand(std::time(nullptr));
int arr[num];
for (int i = 0; i < num; ++i)
arr[i] = std::rand() % num;
findmin(arr, num);
std::cout << cnt;
return 0;
}
int findmin(const int a[], int n)
{
cnt++;
if(n == 0)
return a[0];
int min;
return a[n] < (min = findmin(a, n - 1)) ? a[n] : min;
}
In my mind this algorithm goes down the last element, grabs it and comes back from recursion, compares it to an element and goes on, thus in my mind this is O(2*n).
In another way if we have array 3, 5, 7, 1, 2, 6, recursively we go down and grub 6. On our way up we find that 2 is smaller than 6 so we grub 2. Than we go up and compare it to 1 grub 1 and go up, comparing it to 7, 5, 3. So that is O(n). We are going through array n times. I would really appreciate if somebody can explain this to me.
Here is my source https://stackoverflow.com/a/50034011/5550963