繁体   English   中英

使用分而治之的整数序列的平均值

[英]Average of a sequence of integers using divide and conquer

给定一个整数序列,如何使用分治法找到其平均值? 我必须编写一个方法“ double avg(int [] a,int l,int r)”,该方法在数组A中查找平均值,作为作业的范围从'l'到'r',但是在该方法上我得到了StackOverflowError第一次递归调用-但是不在第二次! -我的代码,而我似乎无法理解原因。 另外,我很确定它不会给我真实的平均值,但是我发现没有办法使用分治法来检查序列的平均值。 这是我的代码:

public class Average {
public static void main(String[] args) {

    int[] A = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    int l = 0;
    int r = A.length-1;
    System.out.println("Average of the array: "+averageCheck(A, l, r));

}

public static double averageCheck(int[] A, int l, int r) {
    if (l==r) {
        return A[l];
    }
    // Base Case: if there's just a single element it is the average of the array itself

    int mid = (l+r)/2;
    double avLeft = 0;
    double avRight = 0;

    avLeft = A[l]/r + averageCheck(A, l, mid);
    avRight = A[mid+1]/r + averageCheck(A, mid+2, r);

    double average = ( (avLeft*mid) + (avRight * (r-mid) ) ) /r;

    return average;

    }
}

r == l + 1时,递归不会结束。 在这种情况下, mid == l ,在第二个递归调用中, mid+2将大于r。 在函数的开头添加以下内容:

if(l > r)
       return 0;

例如,假设l == 5r == 6 ,那么mid将具有值5。第二个调用将是averageCheck(A, 7, 6)因为mid+2为7。在此调用中,条件l == r将为false 以相同的逻辑继续,您将发现递归不会结束。

我还认为,如果递归计算总和并除以长度,那会更好。

我建议这种解决方案:

public class Average {
public static void main(String[] args) {

    int[] A = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
    System.out.println("Average of the array: "+average(A));

}

public static double average (int[] A) {
       return averageCheck(A, 0, A.length - 1) / A.length;
}

public static double averageCheck(int[] A, int l, int r) {

if (l > r)
    return 0;

if (l==r) {
    return A[l];
}
// Base Case: if there's just a single element it is the average of the array itself

int mid = (l+r)/2;
double avLeft = 0;
double avRight = 0;

avLeft = averageCheck(A, l, mid);
avRight = averageCheck(A, mid+1, r);

double average = avLeft + avRight;

return average;

}
}

暂无
暂无

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

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