简体   繁体   English

通过划分数组递归计算总和

[英]Compute the sum recursively by dividing array

I'm trying to create a function to compute the sum of elements in the array recursively.我正在尝试创建一个函数来递归计算数组中元素的总和。 I wanted to try the approach of halving the array every iteration.我想尝试每次迭代将数组减半的方法。

Here's what I have so far.这是我到目前为止所拥有的。

int sumRec(int *A, int n, int start, int end)
{
     if (start == end){
         return A[end];
     }
     mid = n/2;
     return sumRec(A, n, start, mid) + sumRec(A, n, start, mid + 1);
}

Am I on the right track?我在正确的轨道上吗? Thanks.谢谢。

You don't need to pass n to the function.That's not needed.您不需要将 n 传递给函数。那是不需要的。 Currently your program will run into an infinite recursion.目前您的程序将遇到无限递归。

You can use您可以使用

mid = (start+end)/2;

There are many more errors in your code.您的代码中还有更多错误。

Here's a similar code that could do the job这是一个可以完成这项工作的类似代码

int sumRec(int *A, int start, int end)
{
     if (start <= end)
     {
        int mid = (start+end)/2;
        return A[mid] + sumRec(A,start, mid-1) + sumRec(A,mid+1,end);
     }
     return 0;
}

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

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