简体   繁体   English

使用集合对数组进行排序,排序ArrayList

[英]Sorting Array ,Sorting ArrayList ,using Collections

Ok,still learning Arrays. 好的,还在学习阵列。 I wrote this code which fills the array named "rand" with random numbers between 0 and 1( exclusive). 我编写了这段代码,用0和1之间的随机数填充名为“rand”的数组(不包括)。 I want to start learning Complexity. 我想开始学习复杂性。 the For loop executes n times (100 times) ,every time it takes O(1) time,so the worse case scenario is O(n),am I right? For循环执行n次(100次),每次需要O(1)时间,所以更糟糕的情况是O(n),我是对的吗? Also,I used ArrayList to store the 100 elements and I imported "Collections" and used Collections.sort() method to sort the elements. 此外,我使用ArrayList存储100个元素,我导入了“Collections”并使用Collections.sort()方法对元素进行排序。

import java.util.Arrays;
    public class random
    {
        public static void main(String args[])
        {
            double[] rand=new double[10];

                    for(int i=0;i<rand.length;i++)
                    {
                        rand[i]=(double) Math.random();
                        System.out.println(rand[i]);
                    }   

                    Arrays.sort(rand);
                    System.out.println(Arrays.toString(rand));
        }
    }

ArrayList: 数组列表:

import java.util.ArrayList;
import java.util.Collections;

public class random
{
    public static void main(String args[])
    {
        ArrayList<Double> MyArrayList=new ArrayList<Double>();


        for(int i=0;i<100;i++)
        {               
            MyArrayList.add(Math.random());
        }

        Collections.sort(MyArrayList);


        for(int j=0;j<MyArrayList.size();j++)
        {
            System.out.println(MyArrayList.get(j));
        }

    }
}

Yes you are correct, the complexity of adding N items is O(N). 是的,你是对的,添加N项的复杂性是O(N)。 Sorting will take an additional O(N * log(N)) in most cases according to the docs: 根据文档,在大多数情况下,排序将需要额外的O(N * log(N)):

The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 排序算法是一个经过调整的快速排序,改编自Jon L. Bentley和M. Douglas McIlroy的“工程排序功能”,软件实践和经验,卷。 23(11) P. 1249-1265 (November 1993). 23(11)P。1249-1265(1993年11月)。 This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance. 该算法在许多数据集上提供n * log(n)性能,导致其他快速降序降级为二次性能。

ArrayList is still backed by an array, so the complexities will be the same, bar the occasional resizing which is amortized anyway. ArrayList仍然由一个数组支持,因此复杂性将是相同的,无论如何都会偶尔调整大小。

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

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