What is the time complexity of java.util.Collections.sort() method?

﹥>﹥吖頭↗ 提交于 2019-12-18 04:33:26

问题


I have written the following class:

public class SortingObjectsWithAngleField implements Comparator<Point> {  
    public int compare(Point p1, Point p2) {
        double delta = p1.getAngle() - p2.getAngle();
        if(delta == 0.00001)
            return 0;
        return (delta > 0.00001) ? 1 : -1;
    }
}

Then, in my main() method, I have created a List to which I add some objects which has "X" and "angle" field.

I then use:

Collections.sort(list, new SortingObjectsWithAngleField());

What is the complexity of this sort method?


回答1:


You could have read up the docs on Collections sort, but here it is for you:

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance.

Your Comparator doesn't change this complexity, unless you do anything with loops over your collection in it, which you don't.




回答2:


You should have found it in the API: n log(n).




回答3:


Taken from Collections.sort -

The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance




回答4:


Everyone has stated the API doc, adding some more relevant information which I found.

If you provide custom comparator, then a modified version of mergesort (also known as timsort) is used. The implementation has been borrowed from list sort for python.

In the best case as few as n-1 comparisons are needed, so best case is O(n) and guaranteed performance in all the cases is O(n.lg(n))



来源:https://stackoverflow.com/questions/4254122/what-is-the-time-complexity-of-java-util-collections-sort-method

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