Algorithm complexity: is it the same as iterating an array from the beginning than from the end?

In an interview I was offered the following:

public class Main {

public static void main(String[] args) {
    // TODO Auto-generated method stub

    int [] array = new int [10000];

    for (int i = 0; i < array.length; i++) {
       // do calculations   
    }

    for (int x = array.length-1; x >= 0; x--) {
       // do calculations   
    }


}

}

Is it the same as iterating an array either from the very end or from the very beginning? As far as I understand, this would be the same, since the complexity is constant ie O (1)? I'm right?

I was also asked about the complexity of ArrayList compared to other collections in java like LinkedList.

Thank.

+4
source share
3 answers

There may be a difference depending on the characteristics of the processor prefetch.

. , prefetcher, , , .

, Intel Sandy Bridge prefetcher, ( ). ( L1), , , , , .

.

+4

O (n) , n , O (1) ( , O (1)). , O (1) ArrayList.

- ( , ).

, , O (nΒ²), O (n) . , java.util.LinkedList , O (n) java.

, O (n), O (nΒ²).

+1

, , ? , , i.e O (1)? ?

, , , .
- O (10000), , O (1), , . , 10000 , N, , O (N).

ArrayList java, LinkedList.

ArrayList LinkedList. add, remove get. http://www.programcreek.com/2013/03/arraylist-vs-linkedlist-vs-vector/

In addition, LinkedList data is not stored sequentially. However, data in ArrayList is stored sequentially, and ArrayList uses less space than LinkedList Good luck!

0
source

Source: https://habr.com/ru/post/1666804/


All Articles