Java – how to use recursion to check whether all values in an array are equal?

I try to solve this algorithm recursively; I want to check that all values in the array are the same (or equal to each other) Returns true if all values are equal, and false if they are not equal My code failed any tests

public boolean allEqual(int[] a,int start,int end){
    if (start > end) return false;
    if (a.length==0) return false;
    if (start==end && a[start] == a[end]) return true;
    if (a[start] != a[end]){
        return false;
    }
    return allEqual(a,start++,end);
}

Solution

change

return allEqual(a,end);

to

return allEqual(a,start+1,end);

Start passes the original value of start to the recursive call (which is returned by the post increment operator), so your recursion will never end, and you may get a stackoverflowerror

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>