Given an integer array a of size n, write a tail-recursive function with prototype
int f(int a[], int n);
that finds the minimum element of the array.
This is the best I managed to come up with:
int f(int a[], int n)
{
   static int *min;
   if (min == 0)
      min = new int(a[n - 1]);
   else if (*min > a[n - 1])
      *min = a[n - 1];
   if (n == 1)
      return *min;
   else
      return f(a, n - 1);
}
Can it get better? I do not like the use of a static variable.
int f(int a[], int n)
{
    if (n == 1)
        return a[0];
    n--;
    return f(a + (a[0] > a[n]), n);
}
                        kmkaplan's solution is awesome, and I upvoted him. This would have been my not as awesome solution:
int f(int a[], int n)
{
    if(n == 1)
        return a[0];
    n--;
    if(a[0] > a[n])
        a[0] = a[n];
    return f(a, n);
}
The smallest element of the array, at any given time, is stored in a[0]. I originally included a non-modifying version, but then it occurred to me that it was not tail-recursive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With