Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the Minimum Element of an Array Using Tail-Recursion

Tags:

c++

algorithm

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.

like image 472
wjm Avatar asked Nov 30 '22 22:11

wjm


2 Answers

int f(int a[], int n)
{
    if (n == 1)
        return a[0];
    n--;
    return f(a + (a[0] > a[n]), n);
}
like image 56
kmkaplan Avatar answered Dec 04 '22 07:12

kmkaplan


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.

like image 41
Nik Bougalis Avatar answered Dec 04 '22 05:12

Nik Bougalis