Time complexity of Array Manipulation

2019-08-07 01:26发布

Couple very basic time complexity related questions here:

  1. What is the time complexity of array initialization in java? e.g.,

    int arr[] = new int[5000];

    I am guessing it to be O(n) or does the JVM invokes some crazy hardware voodoo magic that it takes only O(1)?

  2. What about inserting or retrieving elements using array index?

    void setNumber(int number, int arrIndex) {
      arr[arrIndex] = number;
    }
    
    int getNumber(int arrIndex) {
      return arr[arrIndex];
    }
    

    I am guessing this to be O(1). But say if arrIndex is 4999 then, wouldn't the pointer that is pointing to the head of the array calculates that the item to be retrieved is at head+(size of int)*arrIndex and 'moves' n (~5000) position to retrieve that item thus making the complexity O(n) and not O(1).

    Perhaps we do not consider things at hardware level and conveniently call it the 'constant' associated with the time complexity? Could someone please clarify? Thanks!

1条回答
2楼-- · 2019-08-07 02:08

You've asked about two thing, which are usually O(1). The former is more complex than the latter, so I will address them in reverse order.

Array Indexing

Recall that 'RAM' stands for "Random Access Memory". This means that (cache effects aside) accessing one portion of ram will be equally as fast as accessing any other. This "moving" of n you refer to simply doesn't happen; the ram circuitry is designed such that whatever you set the address pins to will be on the output pins the next cycle.

Memory Allocation

This is complicated by the fact that there's an allocator doing a bunch of work behind the scenes. There's a wealth of information on Wikipedia, but in a general (but ugly) sense, the answer here is "O(1) except when it isn't."

Even if the array was guaranteed to be zero-filled, you could still see O(1), since many platforms map memory which has already been zero-filled into your process. If you're really curious you could look at the calloc(zero-filled allocation) implementation in Doug Lea's Malloc. Of course, to undersand what goes on below that, you'll need another book, or have to venture into the kernel source.

查看更多
登录 后发表回答