简体   繁体   English

如何对气泡进行反向排序?

[英]How can I sort this Bubble Sort in reverse?

I've got my bubble sort to sort my objects (eventually). 我已经对气泡进行排序以对对象进行排序(最终)。 However, they are printing in ascending order instead of descending order. 但是,它们以升序而不是降序打印。 I'm aware I could use a Collections.Reverse on the array, as far as I know, but (and yes this is a sort of "homework") I can't use that. 据我所知,我可以在数组上使用Collections.Reverse,但是(是的,这是一种“作业”),我不能使用它。

private void bubbleSort()
{
  for (int i = 0; i < employees.size() - 1; i++)
  {
     for (int j = 0; j < employees.size() - i -1; j++)
     {
        if (employees.get(j).compareTo(employees.get(j+1)) > 0)
        {
           Employee temp = employees.get(j+1);
           employees.set(j+1, employees.get(j));
           employees.set(j, temp);
        }
     }
  }
}

Basically what I'm wondering, is there a way I can change a minus to plus or a less than to a greater than and have it sorted the opposite way? 基本上,我想知道的是,是否有一种方法可以将减号更改为正号或小于号,再将其更改为大于号,并以相反的方式进行排序? Thanks. 谢谢。

Change this line 更改此行

if (employees.get(j).compareTo(employees.get(j+1)) > 0)

to this 对此

if (employees.get(j).compareTo(employees.get(j+1)) <= 0)

and it will sort in the reverse order. 它将以相反的顺序排序。

好了,您可以更改compareTo方法的实现,那样就根本不需要调整此代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM