So I'm trying to write a function that sorts a string alphabetically. Here is what I've done:
public static String stringSort(String s) {
if(s.length()<2) {
return s;
}
String recursion = stringSort(s.substring(0, s.length()-1));
recursion += s.substring(recursion.length());
if(recursion.charAt(recursion.length()-2)<recursion.charAt(recursion.length()-1)) {
return recursion;
}
char a = recursion.charAt(recursion.length()-2);
char b = recursion.charAt(recursion.length()-1);
if(recursion.length()>2) {
recursion = recursion.substring(0, recursion.length()-2)+b+a;
} else {
recursion = ""+b+a;
}
String recursion2 = stringSort(recursion);
return recursion2;
}
Basically, it checks the first two letters, swaps if needed and checks again or it continues to check the next two letters.
It seems to work for some words (I tried man and superman), but I get a stack overflow error for other words (splendid). Is there a more efficient way of doing this so I don't get stack overflow?