简体   繁体   English

递归查找数组的最大值

[英]Finding the maximum of an array recursively

I am learning recursion. 我正在学习递归。 As an exercise I am trying to find the maximum of an array recursively. 作为练习,我试图递归地找到数组的最大值。

int recursive (int *arr, int n, int largest) {
  if(n==0)
    return largest;
  else {
    if (*(arr+n)>largest) {
      largest = *(arr+n);
      recursive(arr, n-1, largest);
    }
  }
}

int main() {
  int length = n-1;
  int largest = v[0];
  int z = recursive(arr, length, largest);

  printf("\n%d", z);
}

I followed your suggestions, using pointers instead of arrays, and probably the program looks way better. 我遵循了您的建议,使用指针而不是数组,并且该程序看起来可能更好。 But still it is not doing it's not showing the maximum correctly. 但是它仍然没有这样做,没有正确显示最大值。 I think the logic is correct. 我认为逻辑是正确的。

In C usually you can't declare an array whose size is unknown at compile-time, hence int v[n] is dangerous code. 在C语言中, 通常无法声明在编译时大小未知的数组,因此int v[n]是危险代码。
Depending on your compiler and the compiler's settings this could be a compile error or it could be a bug. 根据您的编译器和编译器的设置,这可能是编译错误,也可能是错误。

For such problems you need to learn about pointers and dynamic memory allocation . 对于此类问题,您需要了解指针和动态内存分配

Side-note: After C99 there are stuff like Variable Length Arrays but the rules are a little advanced. 旁注:C99之后有诸​​如可变长度数组之类的东西,但是规则有些高级。

Also to pass an array to a function you give the array a pointer as an argument: 另外,要将数组传递给函数,您还可以给数组一个指针作为参数:

int z = recursion(v, n, v[0]);

instead of: 代替:

int z = recursion(v[n], n, v[0]);

First thing pay attention to compiler warnings, your recursive function doesn't return value when you enter the else part. 首先要注意编译器警告,当您输入else部分时,递归函数不会返回值。

Now the second thing is please don't use things like *(arr+n) which is hard to read instead use arr[n], also while just a preference when using arrays as function arguments use int arr[] to call the function instead of int *arr (in the first version it's clear you should pass an array). 现在第二件事是,请不要使用*(arr + n)之类的难以理解的东西,而应使用arr [n],同时在将数组用作函数参数时仅使用int arr []来调用该函数而不是int * arr(在第一个版本中,很明显,您应该传递一个数组)。

Third thing is to name your things instead of int recursive describe what the function is doing for example int maxElemRecursive 第三件事是命名您的东西,而不是int recursive描述函数正在执行的操作,例如int maxElemRecursive

So your recursive function should be something like 所以你的递归函数应该是这样的

int maxElemRecursive(int arr[],int n,int largest)
{
    if(n==0) return largest;
    if(arr[n] > largest) // No need for else because return largest; would've returned value;
    {
        largest = arr[n]; 
    }
    return maxElemRecursive(arr,n-1,largest); // You have to return the value of the function.
                                             // You still pass the array with just arr.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM