简体   繁体   中英

Why is my function not giving correct output?

My function checks that whether an array is sorted or not using recursion. Unfortunately, it is returning false for every array.

Function call : sorted(a,0,a.length) where a[] = {1,2,3}; 

boolean sorted(int[] a , int s , int n)
{
    if(s+1==n)
        return true ;
    if(a[s]<=a[s+1])
        sorted(a,s+1,n);
    return false ;
}

You are ignoring the result of the recursive call to sorted . Just return it, and you should be fine:

boolean sorted(int[] a , int s , int n)
{
    if(s+1==n)
        return true ;
    if(a[s]<=a[s+1])
        return sorted(a,s+1,n); // Here!      
    return false ;
}

You don't use result of recursive call. Perhaps it may look like

 if(a[s]<=a[s+1])
      return sorted(a,s+1,n)
 else
     return false;

or (if Java uses fast evaluation of complex conditions):

return (a[s]<=a[s+1]) && (sorted(a,s+1,n))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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