简体   繁体   中英

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.

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方法的实现,那样就根本不需要调整此代码。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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