简体   繁体   English

排序:计算操作并评估运行时复杂性,

[英]Sorting: count operations and assess the run-time complexity,

I am trying to use the system clock (in milliseconds) to count operations and assess the run-time complexity, ( O(N) , O(N^2) , O(1) ) for Collections.sort() . 我正在尝试使用系统时钟(以毫秒为单位)来计数操作并评估Collections.sort()的运行时复杂度( O(N)O(N^2)O(1) Collections.sort() I have somehow come to conclusion that Collections.sort() is O. But from what I see in my code, it is not. 我以某种方式得出结论, Collections.sort()是O。但是从我在代码中看到的事实来看,事实并非如此。 How can I improve my code below. 我如何改善下面的代码。

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

Look at the implementation note for Collections.sort() . 查看Collections.sort()的实现说明。 It specifies that Collections.sort implementation should use iterative merge sort : 它指定Collections.sort实现应使用迭代合并sort:

Implementation note: This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. 实施注意事项:此实现是一种稳定的,自适应的,迭代的归并排序,当对输入数组进行部分排序时,所需的比较少于n lg(n),而当对输入数组进行随机排序时,它提供了传统归并排序的性能。 If the input array is nearly sorted, the implementation requires approximately n comparisons. 如果输入数组几乎已排序,则该实现需要大约n个比较。 Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays. 临时存储要求从几乎排序的输入数组的小常数到随机排序的输入数组的n / 2个对象引用,不等。

This should give you an estimate of the runtime conplexity of Collections.sort(). 这应该使您对Collections.sort()的运行时复杂度有一个估计。 It will vary depending on how much partially sorted your list is. 具体取决于列表的部分排序程度。 The upper bound being O(n logn) 上限为O(n logn)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM