使用尾递归查找数组的最小元素

时间:2021-01-25 19:44:32

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

给定大小为n的整数数组a,用原型编写尾递归函数

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.

可以变得更好吗?我不喜欢使用静态变量。

2 个解决方案

#1


17  

int f(int a[], int n)
{
    if (n == 1)
        return a[0];
    n--;
    return f(a + (a[0] > a[n]), n);
}

#2


2  

kmkaplan's solution is awesome, and I upvoted him. This would have been my not as awesome solution:

kmkaplan的解决方案非常棒,我赞成他。这可能是我不那么棒的解决方案:

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.

在任何给定时间,数组的最小元素存储在[0]中。我最初包含了一个非修改版本,但后来我发现它不是尾递归的。

#1


17  

int f(int a[], int n)
{
    if (n == 1)
        return a[0];
    n--;
    return f(a + (a[0] > a[n]), n);
}

#2


2  

kmkaplan's solution is awesome, and I upvoted him. This would have been my not as awesome solution:

kmkaplan的解决方案非常棒,我赞成他。这可能是我不那么棒的解决方案:

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.

在任何给定时间,数组的最小元素存储在[0]中。我最初包含了一个非修改版本,但后来我发现它不是尾递归的。