I have an assignment where I need to create a recursive method to sort a string lexicographically.
For example:
If the user enters "testing"
The output should be "eginstt"
My code is working, but we are graded on efficiency so I was wondering if there is a simpler way to do it that I'm missing.
I appreciate any feedback.
Thanks
import java.util.Scanner;
public class HWTesting1 {
public static void main(String[] args) {
Scanner scan1 = new Scanner(System.in);
String input = scan1.nextLine();
System.out.println(recurse(input));
}
private static String recurse(String s)
{
//if the string is not null
if(s.length()>=1){
//create a string to add letters in order
String temp = s.substring(0,1);
//loop through each letter and compare it to the one that is currently earliest in order
for(int i=1;i<s.length();i++){
if(s.substring(i,i+1).compareTo(temp)<0)
//add the earliest letter
temp = s.substring(i,i+1);
}
//return the letters first lexicographically and then call the method again with a revised string not containing those letters anymore
return handleDuplicates(s, temp) + recurse(s.replaceAll(temp,""));
}
return "";
}
private static String handleDuplicates(String s, String temp){
String n = "";
//loop through the string to find duplicates of the first letter lexicographically
for(int i=0;i<s.length();i++){
if(s.substring(i,i+1).equals(temp))
n+=s.substring(i,i+1);
}
return n;
}
}

New Topic/Question
Reply



MultiQuote





|