Search code examples
javaarraylistbubble-sort

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?


Solution

  • In your loop:

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

    You should change:

    out > 1

    To:

    out > 0