Monday, 9 September 2013

Better way to alphabetically sort a String?

Better way to alphabetically sort a String?

I have a method that accepts a String parameter and returns that String
sorted alphabetically.
The code as follows:
public static String sort(String s){
String out = "";
String[] ss = new String[s.length()];
for (int i=0;i<s.length();i+=1){
ss[i] = ""+s.charAt(i);
}
for (int i=0;i<ss.length;i+=1){
for (int j=i+1;j<ss.length-1;j+=1){
if (ss[i].compareTo(ss[j])>0){
String tmp = ss[i];
ss[i] = ss[j];
ss[j] = tmp;
}
}
}
for (String st : ss){
out += st;
}
return out;
}
Now, because this method will be run up to 1000 times when used for
processing through multiple Strings, I was wondering if there is anyway to
do this that may significantly reduce overhead?
At the moment it doesn't take much time to execute, with about 10000 calls
being completed in only 0.031s.
This isn't very much at the moment, but I was just wondering if there was
any method which would work in a quicker fashion.
BTW: I'm not explicitly trying to micro-optimize, I'm just curious for
future reference

No comments:

Post a Comment