Chris Chambers
Chris Chambers

Reputation: 1365

Java: Bubble sort somehow not working

Ok, this is really embarrassing, but I have a bubble sort that doesn't seem to fully sort the data each time. I have gone over it even on paper, but I can't find any problems with it. (The below is supposed to sort the largets to the left, and the smallest to the right.

 //Sort multiplicity by number of each card, bubble sort
        int out, in;
        for (out = multi.size() - 1; out > 1; out--) {
            for (in = 0; in < out; in++) {
                if (multi.get(in).getValue() < multi.get(in + 1).getValue()) {
                    CardMultiplicity temp = multi.get(in);
                    multi.set(in, multi.get(in+1));
                    multi.set(in+1, temp);
                }
            }
        }

Note: multi is an Arraylist of a particular type, which shouldn't be important here. Generally, I get it almost sorted, but it seems like it is one pass short sometimes. Is something missing here?

Upvotes: 1

Views: 213

Answers (2)

Sushim Mukul Dutta
Sushim Mukul Dutta

Reputation: 777

the first loop runs till out<1 hence the it does not reaches the 0th row, since the inner loop also runs till the out value. correction required.

for (out = multi.size() - 1; out > 0; out--)//should do the trick

Upvotes: 1

Maroun
Maroun

Reputation: 95968

In your loop:

for (out = multi.size() - 1; out > 1; out--) {

You should change:

out > 1

To:

out > 0

Upvotes: 4

Related Questions