【问题标题】:The Running Time For Arrays.Sort Method in JavaJava中Arrays.Sort方法的运行时间
【发布时间】:2014-01-19 17:01:04
【问题描述】:

有谁知道 arrays.sort java 方法的大 O 表示法的运行时间?我的科学博览会项目需要这个。

【问题讨论】:

    标签: java performance


    【解决方案1】:

    来自官方docs

    我观察到主要有两种方法。因此,这取决于您要排序的内容以及您调用的 sort 系列方法中的重载方法。

    文档提到对于原始类型,例如longbyte(例如:static void sort(long[])):

    排序算法是经过调整的快速排序,改编自 Jon L. Bentley 和 M. Douglas McIlroy 的“设计排序函数”, 软件实践与经验,卷。 23(11) P. 1249-1265(11 月 1993)。该算法在许多数据集上提供 n*log(n) 性能 这会导致其他快速排序降低到二次性能。

    对于对象类型:(例如:void sort(Object list[])

    保证 O(nlogn) 性能

    排序算法是一种修改过的归并排序(其中归并是 如果低子列表中的最高元素小于 高子列表中的最低元素)。该算法提供保证 n*log(n) 性能。

    希望有帮助!

    【讨论】:

    • 我也看到了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. 好像算法取决于你的排序...
    • @csmckelvey 是的,它被称为Tim sort
    【解决方案2】:

    Arrays.sort() 使用 Tim sort - O(N log N) 用于对象数组,QuickSort 用于基元数组 - 再次为 O(N log N)。

    以下是排序算法的精彩对比:http://www.sorting-algorithms.com/

    【讨论】:

      【解决方案3】:

      我已经在各种数据集中测试了 Arrays.sort() 的时间复杂度。在最坏的情况下,它是 O(n^2) 时间复杂度。 尝试使用 Arrays.sort() 做这个问题,然后使用 Collections.sort()。你会看到不同之处。 Question link 当我使用 Arrays.sort() 时,它花了超过 2 秒。 当我使用 collections.sort() 时,花了 0.2 秒 Collections.sort() 使用修改后的合并排序,而 Arrays.sort() 使用 QuickSort()。如果您使用 Array,下面的代码是在 java 中排序的最佳方法。如果是列表,您可以默认使用 Collections.sort()。

      static void sort(long[] a) {
          ArrayList<Long> l=new ArrayList<>();
          for (long i:a) l.add(i);
          Collections.sort(l);
          for (int i=0; i<a.length; i++) a[i]=l.get(i);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-30
        • 2018-05-28
        • 2015-05-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多