Reputation: 2268
I know there's an easy way of doing this... that being said, I'm trying to sort a string using selection sort and stringBuilder class, but I'm getting an infinite loop. If anyone could help, appreciated. package Chapter9Str; import java.util.*;
public class SortedString {
public static void main(String[] args) {
String input = "cabed";
System.out.println(sort(input));
}
public static String sort(String str) {
StringBuilder sb = new StringBuilder(str);
for(int i=0; i<sb.length()-1; i++) {
char tmp;
for(int j=i+1; j<sb.length(); j++) {
if(sb.charAt(j) < sb.charAt(i)) {
tmp = sb.charAt(i);
sb.insert(i, sb.charAt(j));
sb.insert(j, tmp);
}
}
}
return sb.toString();
}
}
Upvotes: 1
Views: 625
Reputation: 33341
Each time to swap, you are actually increasing the length of the string.
if(sb.charAt(j) < sb.charAt(i)) {
tmp = sb.charAt(i);
sb.insert(i, sb.charAt(j));
sb.insert(j, tmp);
}
Insert makes room at the specified location, rather than replacing the char there. for instance, if you start with acbd
, after you've hit that section of code, you'll be left with abccbd
, rather than abcd
.
I think what you are looking for is the setCharAt method.
Upvotes: 3