Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

This program is suppose to sort the the Strings from long to small. What am I doing wrong ?

/*
    Try this 5-1

    Demonstrate the bubble sort.
*/

class Bubble {

    public static void main(String[] args) {
        String sentences[] =
                {"1There is the so called first sentence. ",
                        "2There is the second sentence",
                        "3There is a third sentence",
                        "4many sentences,",
                        "5Lots of sentences,"};

        int a, b;
        String t; //exchange
        int size = sentences.length;
        System.out.print(size);

        // This is the bubble sort
        for (a = 1; a < size; a++) {
            for (b = size - 1; b > a; b--) {
                if (sentences[b - 1].length() >  sentences[b].length()){ // if out of order
                    // Exchange elements
                    t = sentences[b - 1];
                    sentences[b - 1] = sentences[b];
                    sentences[b] = t;
                    for (String y : sentences){

                        System.out.print(y + "\n");



                    }
                    System.out.println();
                }
            }
        }



       }




    }

1 Answer

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

This "bubble sorting" is very hard ...

Since you probably not so sure what is going on your self, I suggest you find working examples of "bubble sorting" in the web and try to change their code to yours:

http://www.java-examples.com/java-bubble-sort-example http://www.java2novice.com/java-interview-programs/bubble-sort/

All I can do from my side ...

I changed almost randomly this line:

// now b>=a not b>a
for (b = size - 1; b >= a; b--) {

And now what I have is this:

4many sentences,
5Lots of sentences,
3There is a third sentence
2There is the second sentence
1There is the so called first sentence. 

It is definitely sorted now :) Although not the way you wanted :) but still. From my experience there is often boundary problems with cycle in cycle stuff...