What's the sort order of Java's Collections.sort(list, comparator)? small to big or big to small?

邮差的信 提交于 2019-12-02 19:56:33
Andy Thomas

The sort order is always ascending, where the Comparator defines which items are larger than others.

From the documentation for Collections.sort(List<T> list, Comparator<? super T> c):

Sorts the specified list according to the order induced by the specified comparator.

From the documentation for Comparator.compare(T,T):

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

You (or rather, your comparator) decides.

  • If your Comparator's compare(T o1, T o2) return a negative when o1 is less than o2, you get ascending order (demo on ideone).
  • If your Comparator's compare(T o1, T o2) return a negative when o1 is greater than o2, you get descending order (demo on ideone).

Another way of saying the same thing would be that sort assumes that the comparator orders the two items passed into it from smaller (o1) to greater (o2), and produces an ascending sort consistent with that ordering.

The documentation of Comparator.compareTo(o1, o2) method says

Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

So if you want to sort from natural ordering , that is small to big, then you should write the implementation as defined in the documentation

public int compareTo(Integer o1, Integer o2) {
     int v1 = (o1);
     int v2 = (o2);
     if(v1 == v2) {
        return 0;
     }
     if(v1 < v2) {
        return -1; //return negative integer if first argument is less than second
     }
     return 1;
}

If you want the sorting to be in reverse order, that is big to small

public int compareTo(Integer o1, Integer o2) {
     int v1 = (o1);
     int v2 = (o2);
     if(v1 == v2) {
        return 0;
     }
     if(v1 < v2) {
        return 1;  //do the other way
     }
     return -1;
}

According to the documentation https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator, the sort implementation for Collections.sort(list, comparator) is mergeSort.

Given the result produced by mergeSort is ascending (https://en.wikipedia.org/wiki/Merge_sort), the sort order of Collections.sort(list, comparator) is ascending.

That is to say if the comparator decides that element A is smaller than element B. In the sorted list, element A will be located at a smaller index than element B.

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