java.util.Collections.sort() 方法的时间复杂度是多少?

发布于 2024-10-04 02:33:18 字数 543 浏览 0 评论 0原文

我编写了以下类:

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;
    }
}

然后,在我的 main() 方法中,我创建了一个 List ,向其中添加了一些具有“X”和“angle”的对象场地。

然后我使用:

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

这种排序方法的复杂性是多少?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

和影子一齐双人舞 2024-10-11 02:33:18

您可以阅读有关集合排序的文档,但这里适合您:

排序算法已修改
合并排序(其中合并是
如果最高元素被省略
low 子列表小于最低的
高子列表中的元素)。这
算法提供有保证的 n log(n)
性能。

您的比较器不会改变这种复杂性,除非您对其中的集合进行循环操作,而您却没有这样做。

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.

同展鸳鸯锦 2024-10-11 02:33:18

您应该在 API 中找到它: n log(n)

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

紫竹語嫣☆ 2024-10-11 02:33:18

摘自 Collections.sort -

排序算法已修改
合并排序(其中合并是
如果最高元素被省略
low 子列表小于最低的
高子列表中的元素)。这
算法提供有保证的 n*log(n)
性能

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

留一抹残留的笑 2024-10-11 02:33:18

每个人都说过 API doc,添加了一些我找到的更相关的信息。

如果您提供自定义比较器,则会使用合并排序的修改版本(也称为 timsort)。该实现借用自python 列表排序

在最好的情况下,只需要 n-1 次比较,因此最好的情况是 O(n) 并且在所有情况下保证性能是 O(n.lg(n))< /代码>

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文