With this implementation it is impossible for a list with duplicate elements to be sorted. However, that possibility is easy enough to support:
return (next == null)
|| ((value <= next.value) && next.isSorted());
Now, empty lists are explicitly sorted by the first clause. Lists with an element strictly greater than a previous element are not sorted by the second. And the third says that if the first two values are sorted and the rest of the list is sorted, the list as a whole is sorted.
This works because this uses short circuit Boolean operators. So when next
is null, it doesn't bother to check the rest of the statement (true ||
is always true). And when the current value is greater than the next, it doesn't need to continue (false &&
is always false). Finally, if it makes it to the last clause, it can simply return the result of it. Because it knows that the first clause was false and the second was true; otherwise, it would never have reached the third.
Alternately, you could change the name from isSorted
to isIncreasing
which would better describe what you are actually doing. If that is what you actually wanted to do.
Moving from a recursive solution on Element
to an iterative solution on the linked list would also make sense.
this.next
andthis.value
with what you've shown. It's hard to see why you're explicitly writingthis.
when accessing members, too. \$\endgroup\$public boolean isSorted() { return next == null || value < next.value && next.isSorted(); }
? That said, you may be better with iterative, rather than recursive, code. \$\endgroup\$