java sort array list using bubblesort

别等时光非礼了梦想. 提交于 2020-01-06 19:55:17

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!