I have been working on this for the past 5 hours. For some reason I am not getting the result I am looking for. The method is supposed to sort an ArrayList of items by quantity using bubble sort. Not sure if I am making a mistake but it seems to only sort the first few items and just lists the rest as they are and not in order.
Here is the code:
public static void bubblesrt(ArrayList<Drinks> list)
{
Drink temp;
if (list.size()>1) // check if the number of orders is larger than 1
{
for (int x=0; x<list.size(); x++) // bubble sort outer loop
{
for (int i=0; i < list.size()-i; i++) {
if (list.get(i).compareTo(list.get(i+1)) > 0)
{
temp = list.get(i);
list.set(i,list.get(i+1) );
list.set(i+1, temp);
}
}
}
}
}
and this is the compareTo() method which is located in a Drinks class
public int compareTo(Drinks z)
{
int res=0;
if (quantity < z.quantity) {res = -1;}
if (quantity > z.quantity) {res = 1;}
return res;
}
How do I make this work as intended?
Try changing
to
and
to