I have created this function to check abecedarian with while loop (A word is said to be “abecedarian” if the letters in the word appear in alphabetical order, such as “abdest”)-
public static boolean isAbecedarian(String s) {
int index = 0;
char c = 'a';
while (index < s.length()) {
if (c > s.charAt(index)) {
return false;
}
c = s.charAt(index);
index = index + 1;
}
return true;
}
I want to change this function to a recursive function and I have written this function –
public static boolean isAbecedarianrec(String s){
char first = s.charAt(0);
char second = first ++;
if (first<second){
return isAbecedarianrec(s);
}
return false;
}
recursive function is not working as it should and I am not getting the expected result. Please check and help me to pin point the issue with this function.
Note – As I mentioned this is not a homework question and it is part of my self Java learning.
Typically with recursion you need two things:
The empty string does form a good base case here – it’s trivially abecedarian. So the first part of your recursive method should be to check for the empty string and return
true. This forms the base case that will be the termination of your recursive method in the “happy path” case.Otherwise, you know you have a non-empty string. The recursive decomposition can be achieved by checking its first character, then recursively calling with the rest of the string. However, in order to perform the check, you’ll need to remember what the previous character of the string was (just like
cin the iterative method), so you’ll need an additional argument to the recursive call to act as a sort of variable.This is not uncommon with recursion – often the majority of the work is done in a “helper” method, and the public method just calls this with initial/dummy values.
Putting these together then, a solution would look something like the following: