问题
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;
}
Right now I am so tired I am ready to give up on it. Any help would be appreciated . Thank you in advance.
回答1:
Try changing
list.add(i,list.get(i+1) );
to
list.set(i,list.get(i+1) );
and
for (int i=0; i < list.size()-i; i++)
to
for (int i=0; i < list.size() - x - 1; i++)
回答2:
You have this line:
list.add(i,list.get(i+1) )
Should be:
list.set(i,list.get(i+1) )
来源:https://stackoverflow.com/questions/8121176/java-sort-array-list-using-bubblesort