Skip to content
Advertisement

Java Bubble Sort String ArrayList Object

Can someone find why this isn’t being sorted I can’t seem to find what I have wrong? The output that is being displayed is how I input them after each other thus the sort method isn’t working…

// Sorting Ticket by Alphabetic Order - Method
public void SortTicket() {
    boolean valid = true;

    for (int i = 0; i < tList.size(); i++) {
        valid = false;
        Ticket t1 = (Ticket) tList.get(i);
        Ticket t2 = (Ticket) tList.get(i++);

        if (t1.GetSurname().compareTo(t2.GetSurname()) > 0) {
            tList.remove(t1);
            tList.add(i++, t1);
            valid = true;
        }

    }

    for (int i = 0; i < tList.size(); i++) {
        Ticket tmpTick = (Ticket) tList.get(i);
        System.out.println(tmpTick.ToString());
    }
}

Advertisement

Answer

There are three errors:
1. It does i++ instead of i+1. i++ means: return i then increment its value. So t1 and t2 are the same element.
2. It runs a full scan of the list, while it should stop at tList.size()-1 to avoid an IndexOutOfBoundsException.
3. It isn’t a real bubble sort. You need two loop.

Moreover you never use valid, so it should be removed. I replaced it with a flag that is true if the list is already sorted.

public void SortTicket()
{
    int size = tList.size();
    int end = size-1; // size-1, so you don't get an IndexOutOfBoundsException
    boolean sorted = false;
    for(int i = 0; i < size-1 && !sorted; i++) 
    {
        sorted = true; // if you never execute a swap, the list is already sorted
        for (int j=0; j<end; j++) {
            Ticket t1 = (Ticket) tList.get(j);
            Ticket t2 = (Ticket) tList.get(j+1); // j+1, so you don't change the value of i
            if(t1.GetSurname().compareTo(t2.GetSurname()) > 0)
            { 
                sorted = false;
                tList.remove(j);
                tList.add(j+1, t1); // j+1, so you don't change the value of i
            }
        }
        end--;
    }

    for(int i = 0; i<size; i++)
    {
        Ticket tmpTick = (Ticket) tList.get(i);
        System.out.println(tmpTick.ToString());
    }
}

Lastly, if you’re using generics, you could declare tList as List<Ticket> tList. This way you don’t need to cast the object returned by list.get(index).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement