1

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();       

    }

}
4
  • You're inserting two characters into the string every time around the loop - I doubt that is what you intend. Shouldn't you also be removing two or perhaps replacing them instead? Commented Dec 14, 2012 at 0:22
  • BTW - This is not selection sort this is bubble sort Commented Dec 14, 2012 at 0:26
  • @OldCurmudgeon No it isn't. The swap is hit more often than it needs to be (lowest value could just be tracked in tmp, then swapped at the end of the inner loop), but through the inner loop, i is static, and at the end of each iteration of the outer loop, exactly one more value is guaranteed to be in order, from least to greatest. Commented Dec 14, 2012 at 0:37
  • @femtoRgon - I am clearly not worthy. :) It looks like BS to me. Commented Dec 14, 2012 at 0:54

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.