Clasificación de matriz, clasificación de ArrayList, uso de colecciones

Ok,still learning Arrays. I wrote this code which fills the array named "rand" with random numbers between 0 and 1( exclusive). 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? Also,I used ArrayList to store the 100 elements and I imported "Collections" and used Collections.sort() method to sort the elements.

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

Lista de arreglo:

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

    }
}

preguntado el 01 de septiembre de 12 a las 16:09

1 Respuestas

Yes you are correct, the complexity of adding N items is O(N). Sorting will take an additional O(N * log(N)) in most cases according to the docs:

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. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance.

ArrayList is still backed by an array, so the complexities will be the same, bar the occasional resizing which is amortized anyway.

Respondido el 01 de Septiembre de 12 a las 16:09

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.