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…

JavaScript

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.

JavaScript

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