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

后端 未结 4 1781
挽巷
挽巷 2020-12-15 17:39

I have written the following class:

public class SortingObjectsWithAngleField implements Comparator {  
    public int compare(Point p1, Point p         


        
相关标签:
4条回答
  • 2020-12-15 17:48

    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.

    0 讨论(0)
  • 2020-12-15 18:04

    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))

    0 讨论(0)
  • 2020-12-15 18:07

    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

    0 讨论(0)
  • 2020-12-15 18:10

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

    0 讨论(0)
提交回复
热议问题