Why is accessing any single element in an array done in constant time ( O(1) )?

后端 未结 5 821
灰色年华
灰色年华 2020-12-14 04:32

According to Wikipedia, accessing any single element in an array takes constant time as only one operation has to be performed to locate it.

To me, what happens behi

5条回答
  •  猫巷女王i
    2020-12-14 05:00

    If you have array of Int's. Each int is 32 bit's in java . If you have for example 10 integers in java it means you allocate memory of 320 bits. Then computer know

    0 - index is at memory for example - 39200

    last index is at memory 39200 + total memory of your array = 39200+320= 39520

    So then if you want to access index 3. Then it is 39200 + 32*3 = 39296.

    It all depends how much memory your object takes which you store in array. Just remember arrays take whole block of memory.

提交回复
热议问题