Reputation: 332
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 ;
}
Upvotes: 1
Views: 64
Reputation: 311448
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 ;
}
Upvotes: 4
Reputation: 80197
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))
Upvotes: 1