Finding the smallest array element using tail recursion

For an integer array a size n , write a tail-recursive function with a prototype

 int f(int a[], int n); 

which finds the minimum element of an 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 don't like using a static variable.

+4
source share
2 answers
 int f(int a[], int n) { if (n == 1) return a[0]; n--; return f(a + (a[0] > a[n]), n); } 
+17
source

Kmkaplan's solution is awesome and I supported it. This would be my less frightening decision:

 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 time is stored in [0]. I initially included the version without modification, but then it occurred to me that it was not tail recursive.

+2
source

All Articles