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

后端 未结 5 814
灰色年华
灰色年华 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条回答
  •  天涯浪人
    2020-12-14 04:53

    An array starts at a specific memory address start. Each element occupies the same amount of bytes element_size. The array elements are located one after another in the memory from the start address on. So you can calculate the memory address of the element i with start + i * element_size. This computation is independent of the array size and is therefor O(1).

提交回复
热议问题