【问题标题】:Sorting: count operations and assess the run-time complexity,排序:计数操作并评估运行时复杂度,
【发布时间】:2014-05-15 02:49:10
【问题描述】:

我正在尝试使用系统时钟(以毫秒为单位)来计算操作并评估运行时复杂度,(O(N)、O(N^2)、O(1))对于Collections.sort()。我以某种方式得出结论 Collections.sort() 是 O。但从我在代码中看到的情况来看,它不是。如何改进下面的代码。

public class TestTime {
    public static void main(String[] args) throws FileNotFoundException {
        Random generator = new Random();

        ArrayList<Integer>numbers = new ArrayList<Integer>();

        for (int n = 1000; n < 1000000; n += 2000) {
            numbers.clear();

            for (int i = 0; i < n; i++) {
                numbers.add(generator.nextInt(100) + 1);
            }

            long startTime1 = System.currentTimeMillis();
            Collections.sort(numbers);
            long endTime1 = System.currentTimeMillis();
            System.out.println( n +"," +(endTime1-startTime1));
        }

        System.out.println("Completed Sorting");
    }
}

【问题讨论】:

  • I have somehow come to conclusion that Collections.sort() is O 是什么意思?你的结论是什么?什么是O?您是如何得出这个结论的(somehow 并没有告诉我们太多信息)?

标签: java sorting collections big-o


【解决方案1】:

查看Collections.sort() 的实现说明。它指定 Collections.sort 实现应该使用迭代合并排序:

实现说明:此实现是一种稳定的、自适应的、迭代的归并排序,当输入数组部分排序时,它需要远少于 n 次 lg(n) 比较,同时在输入数组随机排序时提供传统归并排序的性能.如果输入数组接近排序,则实现需要大约 n 次比较。临时存储要求从几乎排序的输入数组的小常数到随机排序的输入数组的 n/2 对象引用不等。

这应该让您估计 Collections.sort() 的运行时复杂性。它会根据您的列表的部分排序程度而有所不同。上限为 O(n logn)

【讨论】:

    猜你喜欢
    • 2017-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 1970-01-01
    • 2012-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多