1

if i do this

int n = some arbitrary number
int[] array = new int[n];

is the time needed linear (O(n)) or constant (O(1))?
i looked in the javadocs and eg. here in StackOverflow but didn't find an answer because all the posts i saw deal with dynamic allocation.

2
  • 1
    you may check this link stackoverflow.com/questions/5640850/… Commented Jun 27, 2016 at 10:30
  • i just didn't find it before ... should i delete the question (its a duplicate after all) Commented Jun 27, 2016 at 10:36

1 Answer 1

1

In java, when you create a new array of int, all members of the array must get the initial value for int (which is '0'), so the initialization includes n assignments of the value 0, thus taking O(n).

You can also verify it, using the following code, with different n's:

public static void main(String[] args)
{
    int n = 1000000;
    int numSamples = 10000;
    long sumTime = 0;
    for (int i = 0; i < numSamples; i++)
    {
        sumTime += test(n);
    }
    double average = sumTime / (double) numSamples;
    System.out.println(average);
}

private static long test(int size)
{
    long start = System.currentTimeMillis();
    int[] a = new int[size];
    return System.currentTimeMillis() - start;
}
Sign up to request clarification or add additional context in comments.

2 Comments

But OP says 'not dynamic' so maybe the compiler does it since s/he doesn't show the 'static' keyword, or perhaps the class loader - just speculating.
Test verifies that it's O(n). Added sample test code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.